文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Version 1
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> result;
for(int i = 0; i < nums.size(); i++) {
int index = abs(nums[i]) - 1;
if(nums[index] > 0) {
nums[index] = -nums[index];
}
}
for(int i = 0; i < nums.size(); i++) {
if(nums[i] > 0) {
result.push_back(i + 1);
}
}
return result;
}
};
- Version 2
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> result;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == i + 1) {
continue;
}
if(nums[i] != nums[nums[i] - 1]){
swap(nums[i], nums[nums[i] - 1]);
i--;
}
}
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != i + 1) {
result.push_back(i + 1);
}
}
return result;
}
private:
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
};