Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
Example 1:
Input: nums = [2,2,1] Output: 1
Example 2:
Input: nums = [4,1,2,1,2] Output: 4
Constraints:
1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
- Each element in the array appears twice except for one element which appears only once.
解法一:遍历数组中的每个数,如果这个数存在集合s中,就从集合中删掉此数,否则,把这个数插入集合中。遍历结束后,集合中剩下的唯一的数就是single number。
时间复杂度O(n),空间复杂度O(n)
class Solution { public: int singleNumber(vector<int>& nums) { unordered_set<int> s; int n=nums.size(); for(int i=0;i<n;i++){ if(s.count(nums[i])) s.erase(nums[i]); else s.insert(nums[i]); } return *s.begin(); } };
Runtime: 32 ms, faster than 20.54% of C++ online submissions for Single Number.
Memory Usage: 19.9 MB, less than 19.77% of C++ online submissions for Single Number.
解法二、用异或运算。一个数与其本身进行异或,等于0,一个数和0进行异或,等于这个数本身。异或运算满足交换律和结合律,即A^B^A=B。
时间复杂度O(n),空间复杂度O(1)
class Solution { public: int singleNumber(vector<int>& nums) { int ans=0; for(int i=0;i<nums.size();i++) ans^=nums[i]; return ans; } };
Runtime: 12 ms, faster than 97.15% of C++ online submissions for Single Number.
Memory Usage: 16.8 MB, less than 97.90% of C++ online submissions for Single Number.