https://leetcode.com/problems/set-mismatch/description/
Solution 0. Use XOR and count numbers
vector<int> findErrorNums(vector<int>& nums) {
vector<int> cnt(nums.size(),0);
vector<int> res = {0, 0};
for(int i=0; i<nums.size(); i++) {
if(++cnt[nums[i]-1] == 2)
res[0] = nums[i];
res[1] ^= (i+1)^nums[i];
}
res[1] ^= res[0];
return res;
}
Solution 1. Sort by putting nums[i] at index nums[i]-1
vector<int> findErrorNums(vector<int>& nums) {
for(int i=0; i<nums.size(); i++) {
while(nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]);
}
for(int i=0; i<nums.size(); i++) {
if(nums[i] != i+1) return {nums[i], i+1};
}
}
Solution 2. Use bitset
vector<int> findErrorNums(vector<int>& nums) {
bitset<10000> bits(0);
vector<int> res;
for(auto n: nums) {
if(bits.test(n-1)) res.push_back(n);
else bits.set(n-1);
}
for(int i=0; i<bits.size(); i++) {
if(!bits[i]) {
res.push_back(i+1);
break;
}
}
return res;
}
No comments:
Post a Comment