Find All Numbers Disappeared in an Array

2019-05-25 22:53:58 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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;
    }
};

0 人点赞