Leetcode 136. 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?

题目要求O(n)时间复杂度,O(1)空间复杂度。

思路:利用异或操作。异或的性质1:交换律a ^ b = b ^ a,性质2:0 ^ a = a。于是利用交换律可以将数组假想成相同元素全部相邻,于是将所有元素依次做异或操作,相同元素异或为0,最终剩下的元素就为Single Number。时间复杂度O(n),空间复杂度O(1)

C++:

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         int len = nums.size(), a = 0;
 5         for(int i = 0; i < len; i++){
 6             a ^= nums[i];
 7         }
 8         return a;
 9     }
10 };

 

c:

1 int singleNumber(int* nums, int numsSize) {
2     int i, a = 0;
3     for(i = 0; i < numsSize; i++){
4         a ^= nums[i];
5     }
6     return a;
7 }


 

 

posted @ 2016-08-02 18:38  琴影  阅读(98)  评论(0编辑  收藏  举报