136. Single Number
by Botao Xiao
Thinking:
- Method 1:sort
class Solution {
public int singleNumber(int[] nums) {
Arrays.sort(nums);
int len = nums.length;
if(len == 1) return nums[0];
if(nums[0] != nums[1]) return nums[0];
for(int i = 1; i < len - 1; i++){
if(nums[i] != nums[i - 1] && nums[i] != nums[i + 1])
return nums[i];
}
return nums[len - 1];
}
}
- Method 2: 异或
- 因为相同的会出现两次,异或会变成0,
- 最后剩下来的就是只出现一次的数。
class Solution {
public int singleNumber(int[] nums) {
int count = 0;
for(int i = 0; i < nums.length; i++)
count ^= nums[i];
return count;
}
}
二刷
异或
class Solution {
public int singleNumber(int[] nums) {
int index = nums[0];
for(int i = 1; i < nums.length; i++){
index ^= nums[i];
}
return index;
}
}
Subscribe via RSS