136. Single Number

Input: nums = [2,2,1]
Output: 1
Input: nums = [4,1,2,1,2]
Output: 4
Input: nums = [1]
Output: 1

解法一

class Solution {
public:
int singleNumber(vector<int>& nums) {

int arr_pos[3*10000+1] = {0};
int arr_neg[3*10000] = {0};

for(int i=0; i<nums.size(); i++){
if(nums[i] >= 0){
arr_pos[nums[i]]++;
}
else{
arr_neg[-(nums[i])]++;
}
}

for(int i=0; i<=3*10000; i++){
if(arr_pos[i] == 1){
return i;
}

if(arr_neg[i] == 1){
return -i;
}
}
return 0;
}
};

解法二

使用XOR

XOR Truth Table
Input: nums = [4,1,2,1,2]
Output: 4

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store