题目来源:https://leetcode.com/problems/single-number/
问题描述
136. Single Number
Easy
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
------------------------------------------------------------
题意
给定一个数组,除了一个元素,其他元素都出现了2次,求只出现了一次的那个元素。
------------------------------------------------------------
思路
解法1:哈希。用一个哈希表记录每个元素出现的次数,时间复杂度O(n),空间复杂度O(n)
解法2:位运算。利用异或运算的两条性质:
(1) 0 ^ x = x
(2) x ^ x = 0
(3) x ^ y ^ x = x ^ x ^ y = (x ^ x) ^ y = y(交换律)
将所有元素异或在一起,根据交换律,可以把所有重复出现的元素凑在一起变成0,最后剩下的就是只出现一次的元素。
时间复杂度O(n),空间复杂度O(1).
------------------------------------------------------------
代码
解法1:
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num: nums) {
map.put(num, map.containsKey(num)? map.get(num)+1: 1);
}
for (int num: nums) {
if (map.get(num) == 1) {
return num;
}
}
return -1; // not found
}
}
解法2:
class Solution {
public int singleNumber(int[] nums) {
int xor = 0;
for (int num: nums) {
xor ^= num;
}
return xor;
}
}