leetcode解题: Single Number (136)

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?

解法1:O(N) time with O(1) space, N is the number of elements

运用XOR是一个抵消运算符,A XOR A 出来是一个0,所以对所有的数字做XOR之后重复的都消掉了,只剩下单独的一个。C++中vector的method是vector.size(),和java中array的array.length注意区分。

C++

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

Java

1
2
3
4
5
6
7
8
9
public class Solution {
public int singleNumber(int[] nums) {
int result = nums[0];
for (int i = 1; i < nums.length; i++) {
result ^= nums[i];
}
return result;
}
}