LeetCode 136. Single Number
Woodyiiiiiii opened this issue · comments
Given a non-empty 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?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
题目意思是一个非空数组中,有一个数出现一次,其他数都出现两次,找出这个只出现一次的数。要求空间复杂度O(1),时间复杂度O(n)。
一开始我是用哈希表的特点,遍历数组元素,如果哈希表中没有出现这个数,那么存进哈希表(key为元素,value是元素下标)。最后哈希表肯定剩下唯一的键值对,返回key就可以了。注意remove(), keySet()方法的使用和遍历哈希表。
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer, Integer> myMap = new HashMap<>();
int i = 0;
for (int num : nums) {
if (myMap.containsKey(num)) myMap.remove(num);
else myMap.put(num, i);
++i;
}
for (Integer key : myMap.keySet()) {
return key;
}
return 0;
}
}
显然这个方法的空间复杂度不是常数级。
对于数,还有位运算的想法,异或的作用是相同的数异或为0,不同的不为0。利用位异或的特点:
- x ^ x = 0
- 0 ^ x = x
可以得到x ^ y ^ x = y的公式。遍历异或数组即可。
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int v : nums) {
result ^= v;
}
return result;
}
}
func singleNumber(nums []int) int {
var res int
for _, v := range nums {
res ^= v
}
return res
}
扩展:如果一次数出现一次,其他数出现偶数次,都可以用异或方法找出。
参考:
LeetCode原题