题目链接:https://leetcode-cn.com/problems/single-number/
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
题意:找到那个只出现一次的元素;
思路:(1)先排序,然后遍历整个数组,找到唯一出现的那个元素;
(2)异或,相同为0,不同为1,两个相同的数最后都会被消掉,留下的就是结果;
代码:
(1)排序后遍历
class Solution {
public:
int singleNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
int ans = nums[0], a = nums[0], b = 1;
for(int i = 1; i < nums.size(); i++){
if(ans != nums[i]){
if(b == 1){
a = ans;
}
b = 1;
}else{
b++;
}
ans= nums[i];
}
if(b == 1){
a = ans;
}
return a;
}
};
(2)异或
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = nums[0];
for(int i = 1; i < nums.size(); i++){
ans = ans ^ nums[i];
}
return ans;
}
};

408

被折叠的 条评论
为什么被折叠?



