leetcode-只出现一次的数字

时间:2023-03-10 00:30:44
leetcode-只出现一次的数字

题目:只出现一次的数字

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1

示例 2:

输入: [4,1,2,1,2]
输出: 4
  • 第一种

使用Hash创建key-value映射

代码:

    public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap();
for (int num : nums) {
map.put(num, map.containsKey(num) ? 0 : 1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return -1;
}
  • 第二种

在解题时应该充分考虑题目所给的条件。

比如“给定一个整数数组,除了某个元素外其余元素均出现两次”,我们由此可以知道,若该数组有序,且有一个元素只出现一次,以步数2向后遍历,那么一定会存在a[i] != a[i+1]

代码:

    public int singleNumber2(int[] nums) {
Arrays.sort(nums); for (int i = 0; i < nums.length ; i = i + 2) {
if (i + 1 >= nums.length ) {
return nums[i];
}
if (nums[i] != nums[i + 1]) {
return nums[i];
}
} return -1;
}
  • 第三种

使用异或:数a两次异或同一个数b(a=a^b^b)仍然为原值a.

异或口诀: 相同取0,相异取1

0^4
0000 0000
0000 0100
=
0000 0100 4^2=6
0000 0100
^
0000 0010
=
0000 0110 6^2=4
0000 0110
^
0000 0010
=
0000 0100

代码:

    public int singleNumber3(int[] nums) {
Arrays.sort(nums);
int res = 0;
for (int num : nums) {
res ^= num;
}
return res; }

参考:https://blog.****.net/biezhihua/article/details/79571917

代码:https://gitee.com/hapzxb/LeetCode/blob/master/leetcode/src/main/java/com/hapzxb/leetcode/array/SingleNumber.java