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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题用异或做太火了。。。。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int num=0;
for(auto it :nums){
num ^= it;
}
return num;
}
};
想了一个,排序然后俩俩一对儿
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n =nums.size();
if(n==1){
return nums[0];
}
sort(nums.begin(),nums.end());
int i=0;
while(i+1<n){
if(nums[i]!=nums[i+1]){
return nums[i];
}
i=i+2;
}
return nums[i];
}
};