zoukankan      html  css  js  c++  java
  • 优酷土豆2012.9.12校园招聘会笔试题

    给你一个由n-1个整数组成的未排序的序列,其元素都是1到n中的不同的整数。请写出一个寻找序列中缺失整数的线性时间算法。

    分析:只要通过异或算法就可实现,由于1^1=0,2^2=0,0^n = 0;因此,数组中的所有数据与1-n一起做异或,缺失的数据就会显现出来,

    代码如下所示:

    int getLostNum(int a[],int n)
    {
    	int result = 0;
    	int loop = 0;
    	int i = 0;
    	for(loop = 1; loop <= n; ++loop)
    	{
    		result ^= loop;
    	}
    	for(i = 0; i < n-1;i++)
    	{
    		result ^= a[i];
    	}
    	return result;
    }
    void main()
    {
    	int num[6] = {1,3,2,4,5,7};
    	int re = 0;
    	re = getLostNum(num,7);
    	cout<<re<<endl;
    
    }
    

      

  • 相关阅读:
    毕业论文格式
    2018.12.14
    关于百度搜索引擎的优缺点
    2018.12.13
    2018.12.12
    2018.12.11
    2108.12.10
    2018.12.9
    2018.12.8
    2018.12.7
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8024447.html
Copyright © 2011-2022 走看看