LeetCode No.448 Find All Numbers Disappeared in an Array

来源:互联网 发布:编程珠玑适合什么人看 编辑:程序博客网 时间:2024/06/05 03:16

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]

===================================================================

题目链接:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/

题目大意:给定一个长度为n的数组,其中1 ≤ a[i] ≤ n ,找出所有不在数组中的[1, n],要求使用时间复杂度为O(N),空间复杂度为O(1)的算法

思路:先对数组进行重组,使得所有存在的i + 1都构成nums[i] = i + 1,剩下不符合这个等式的就是不存在的。

参考代码:

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        int n = nums.size() ;        for ( int i = 0 ; i < n ; i ++ )        {            while ( nums[nums[i]-1] != i )            {                if ( nums[i] == nums[nums[i]-1] )                    break ;                swap ( nums[i] , nums[nums[i]-1] ) ;            }        }        vector <int> ans ;        for ( int i = 0 ; i < n ; i ++ )            if ( nums[i] != i + 1 )                ans.push_back ( i + 1 ) ;        return ans ;    }};


0 0
原创粉丝点击