18
06/2015
[LeetCode] Single Number
Single Number
Given an 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?
解题思路:
解法一:先排序,再遍历。时间复杂度为O(nlogn),空间复杂度为O(1)。代码略。
解法二:用一个set来记录结果,若已经存在,则从set中删除。最终只留下目标数字。时间复杂度为O(n),空间复杂度为O(n)。
解法三:位操作。注意,两个相同数字异或为0,0与任何数字异或等于该数字本身。这样时间复杂度为O(n),空间复杂度为O(1)。
class Solution { public: int singleNumber(vector<int>& nums) { int result = 0; int len = nums.size(); for(int i=0; i<len; i++){ result ^= nums[i]; } return result; } };
转载请注明:康瑞部落 » [LeetCode] Single Number
0 条评论