LeetCode 448 Find All Numbers Disappeared in an Array

来源:互联网 发布:three.js 制作全景图 编辑:程序博客网 时间:2024/06/05 04:29

题目

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]

解法

给定一个整数数组,其中1 ≤ a[i] ≤ n (n = 数组长度),一些元素出现两次,其他的出现一次。如果每个元素只出现一次,则元素与下标的关系为a[i] = i+1。

  • 不使用额外的空间,O(n)的时间复杂度。考虑在当前数组上进行操作,遍历一遍该数组。如果满足nums[i] == i+1的关系,则元素在正确的位置上,如果不满足,则不断的将错误位置上的元素移动到本该属于其的位置上。重新遍历时,nums[i]!=i+1的数字则是没有出现过的元素。
class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        vector<int> res;        for(int i = 0; i < nums.size(); i++)        {            if(nums[i] == i+1)                continue;            else            {                while(nums[nums[i] - 1] != nums[i] )                {                    int temp = nums[nums[i] - 1];                    nums[nums[i] - 1] = nums[i];                    nums[i] = temp;                }            }        }        for(int i = 0; i < nums.size(); i++)        {            if(nums[i] != i+1)                res.push_back(i+1);        }        return res;    }};
  • 在网上看到另一种解法:不移动元素位置,使用正负号标记来确定该数字是否出现。
    元素值的绝对值减一作为下标,该下标对应的值改为负值。
    重新遍历时,元素值为正数的,说明该下标加一的数字没有出现。
class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        vector<int> res;        for (int i = 0; i < nums.size(); i++) {            int index = abs(nums[i])-1;            if (nums[index] > 0 ) {                nums[index] *=-1;            }        }        for (int i = 0; i < nums.size(); i++) {            if (nums[i] > 0)                res.push_back(i+1);        }        return res;            }};
0 0
原创粉丝点击