文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Set Mismatch2. Solution
- Version 1
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<int> result;
int flag[nums.size() + 1] = {0};
for(int index : nums) {
flag[index]++;
}
int duplicate = 0;
int missing = 0;
for(int i = 1; i < nums.size() + 1; i++) {
if(flag[i] == 2) {
duplicate = i;
}
if(flag[i] == 0) {
missing = i;
}
}
result.push_back(duplicate);
result.push_back(missing);
return result;
}
};
- Version 2
class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<int> result;
int duplicate = 0;
int missing = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[abs(nums[i]) - 1] < 0) {
duplicate = abs(nums[i]);
continue;
}
nums[abs(nums[i]) - 1] = -nums[abs(nums[i]) - 1];
}
for(int i = 0; i < nums.size(); i++) {
if(nums[i] > 0) {
missing = i + 1;
}
}
result.push_back(duplicate);
result.push_back(missing);
return result;
}
};
网友评论