Leetcode:448. Find All Numbers Disappeared in an Array

问题描述:
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

难度等级:简单

这个有点小技巧,就是设置index,然后对应数字设成负的,最后只要看对应index的数是正数的,取出对应的index就好了O(∩_∩)O哈哈~

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        for(auto num:nums){
            int index = num>0 ? num:-num;
            index--;
            if(nums[index]>0){
                nums[index] = -nums[index];
            }
        }

        vector<int> result;
        for(int i = 0; i < nums.size(); i++){
            if(nums[i]>0){
                result.push_back(i+1);
            }
        }
        return result;
    }
};

恩恩O(∩_∩)O哈哈~

猜你喜欢

转载自blog.csdn.net/felaim/article/details/80517750