LeetCode-Single Number
原创
©著作权归作者所有:来自51CTO博客作者BeHelium的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description:
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:
Example 2:
Input: [4,1,2,1,2]
Output: 4
题意:给定一个数组,里面包含出现一次或者两次的元素,要求找出只出现了一次的那个元素;
解法一:我们可以利用哈希表来实现,将元素及其出现的次数作为键值对保存在表中,最后遍历表找出出现了一次的那个元素;
Java
class Solution
public int singleNumber(int[] nums) {
Map<Integer, Integer> count = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
}
for (Integer key : count.keySet()) {
if (count.get(key) == 1) {
return key;
}
}
throw new IllegalArgumentException("No such solution");
}
}
解法二:我们可以利用位操作,对于正数a、b、c来说;
- a ^ b ^ b = a; a ^ c ^ c = a;
- a ^ b ^ b ^ c ^ c = a ^ b ^ b ^ (c ^ c) =a ^ c ^ c =a
从上面的等式我们可以看到,a与一个相同的数异或两次等于自身,因此我们可以将数组中的所有数字进行异或操作,最后得到的结果就是只出现了一次的那个数;
Java
class Solution {
public int singleNumber(int[] nums) {
int result = nums[0];
for (int i = 1; i < nums.length; i++) {
result ^= nums[i];
}
return