题目链接:LeeCode136只出现一次的数字
题目描述:
我自己想的方法是排序挨个找,如果当前的跟上一个元素相等那就将flag置成true,当flag为true时即使不相等也能往前走,找到既不和前一个元素相等flag又为false的点就是单独元素
class Solution {
public int singleNumber(int[] nums) {
Arrays.sort(nums);
boolean flag=false;
int index=1;
while (index < nums.length) {
if(nums[index-1]==nums[index]){
flag=true;
}else {
if(flag){
index++;
flag=false;
continue;
}else{
return nums[index-1];
}
}
index++;
}
return nums[index-1];
}
}
然后效率50%,我就找了找题解,人傻了。。。。一看就会,让我自己想这辈子也白费
class Solution {
public int singleNumber(int[] nums) {
for (int i = 1; i < nums.length; i++) {
nums[0]^=nums[i];
}
return nums[0];
}
}