毫无疑问,双重循环肯定是能解决的,但是时间复杂度却是O(n2)。

    解决问题前,先了解一下异或运算。

    运算法则:     

输入 运算 输入 输出
1 1 0
1 0 1
0 1 1
0 0 0

 

 

 

 

    于是,就有了以下的推论:

      1)  a⊕a=0

      2)  0⊕a=a

      3)  a⊕b=b⊕a

      4)  a⊕b⊕c=(a⊕b)⊕c=a⊕(b⊕c)

      5)  d=a⊕b⊕c  ==> a=d⊕b⊕c

      6)  a⊕b⊕a=b⊕a⊕a=a⊕a⊕b=b

     这样就简单了,遍历一次,时间复杂度O(n)。解决方法如下:      

//int数组中的有一个元素只出现一次,其余都出现2次
public int FindElementOneTime(int[] arrInt)
{
      if(arrInt.Length==0)
      {
            return -1;     
      }
      int res=arrInt[0];
      for(int i=1;i<arrInt.Length;i++)
      {
          res ^=arrInt[i];      
      }
      return res;
}

  

 posted on 2014-06-07 10:15  会飞的金鱼  阅读(186)  评论(0)    收藏  举报