leetcode 之Single Number(13)

              看见这题我的第一反应是用哈希来做,不过更简洁的做法是用异或来处理,只要是偶数个都为0(0和任意数异或仍为数本身)。

           

  int singleNumber(int A[], int n)
      {
          int x = 0;
          for (int i = 0; i < n; i++)
              x ^= A[i];

          return x;
      }
View Code

               

              这题的思路更加巧妙,需好好琢磨,思路如下:

            

       

int singleNumber2(int A[], int n)
    {
        int one, two, three;
        one = two = three = 0;

        for (int i = 0; i < n; i++)
        {
            three = two & A[i];//已经出现了两次,再出现了一次
            two = two | (one &A[i]);
            one = one | A[i];

            //去掉出现三次的
            one = one &(~three);
            two = two &(~three);
        }

        return one;
    }
View Code

 

posted @ 2016-05-17 15:14  牧马人夏峥  阅读(92)  评论(0编辑  收藏  举报