leetcode Find All Numbers Disappeared in an Array 找数组中消失的元素

来源:互联网 发布:java中todo 编辑:程序博客网 时间:2024/06/09 17:45

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之间的数,要求时间复杂度为O(n),空间复杂度为O(1);
思路:遍历数组,将数组中元素a[i]对应下标所对应的元素a[a[i]]取负,代表元素a[i]存在,遍历数组,数组中正数元素对应的下标即为消失的元素。
即为节省空间,用原数组元素的正负来标记对应下标数是否存在。

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        int len = nums.size();        vector<int> ans;        for (int i = 0; i < len; ++i) {            int temp = abs(nums[i]) - 1;            nums[temp] = nums[temp] > 0 ? -nums[temp] : nums[temp];        }        for (int i = 0; i < len; ++i) {            if (nums[i] > 0) ans.push_back(i + 1);        }        return ans;    }};
阅读全文
0 0
原创粉丝点击