[Leetcode] single number 找单个数

Given an array of integers, every element appears twice except for one. Find that single one.

Note: 
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

题意:给定一未排序的数组,其中只有一个数仅出现一次,其余都出现两次,找到仅出现一次的这个数。

思路:一般的暴力解法或者先排序,后遍历。显然这两种种做法不行,时间复杂度上没法满足线性。所以采用逻辑异或来解题。逻辑异或有几个特点:

一、异或满足交换律;二、相同两个数异或为0;三、0异或一个数为那个数本身。十位数的异或,先将其转变二进制,然后进行异或。参考了LeetCode OJ代码如下:

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) 
 4     {
 5         int res=0;
 6         for(int i=0;i<n;++i)
 7         {
 8             res^=A[i];
 9         }      
10         return res;    
11     }
12 };

同样的思路还有一种解法,牛客网@setsail,这种解法也是根据相同数异或为0的特性,找到仅出现一次的那个数。

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) 
 4     {
 5         if(n==1)
 6             return A[0];
 7         while(n>=2)
 8         {
 9             A[n-2]^=A[n-1];
10             n--;
11         }
12         return A[0];
13     }
14 };

 

posted @ 2017-07-18 09:35  王大咩的图书馆  阅读(210)  评论(0编辑  收藏  举报