自己解出来运行时间有点长。得学习大牛的了
public int singleNumber(int[] nums) {
int k = 0;
outr:
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[i] == nums[j] && j != i) {
continue outr;
}
}
k = nums[i];
break;
}
return k;
}
public int singleNumber(int nums[]) {
int result = 0;
for (int i = 0; i < nums.length; i++)
result ^= nums[i];
return result;
}
作者:数据结构和算法
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x21ib6/?
public int singleNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
//如果添加失败,说明这个值
//在集合Set中存在,我们要
//把他给移除掉
set.remove(num);
}
}
//最终集合Set中只有一个元素,我们直接返回
return (int) set.toArray()[0];
}
作者:数据结构和算法
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x21ib6/?