leetcode448. Find All Numbers Disappeared in an Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ns708865818/article/details/88261893

题目链接:https://leetcode.com/problems/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]

解题思路:

给定一个大小为N的数组,其中数组的元素都在1和N之间,判断1和N之间的哪个数字在数组中没有出现,其中最简单的方式也是最巧的方式,将数组中有的元素的索引对应的值,如果为正数,则置为负数即可。

代码:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int n = nums.size();
        vector<int> ret ;
        for(int i = 0;i<n;i++){
            if(nums[abs(nums[i])-1]>0)
            {
                nums[abs(nums[i])-1]=-nums[abs(nums[i])-1];
            }
        }
        for(int i = 0 ;i<n;i++){
            if(nums[i] > 0){
                ret.push_back(i+1);
            }
        }
        return ret;
        
    }
};

猜你喜欢

转载自blog.csdn.net/ns708865818/article/details/88261893