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?

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
Arrays.sort(nums);
int l = nums.length - 1;
if (l == 0) {
result = 0;
} else if (nums[l] != nums[l - 1] && nums[l] != nums[l - 2]) {
result = l;
} else if (nums[0] != nums[1]) {
result = 0;
} else {
for (int i = 2; i < l; i++) {
result = i;
if (nums[i] != nums[i + 1] && nums[i] != nums[i - 1]) {
break;
}
}
}
return nums[result];
}
}

参考答案

1
2
3
4
5
6
7
public int singleNumber(int[] nums) {
int ans =0;
int len = nums.length;
for(int i=0;i!=len;i++)
ans ^= nums[i];
return ans;
}