leetcode 448Find All Numbers Disappeared in an Array (array)

来源:互联网 发布:斗鱼刷人气软件源代码 编辑:程序博客网 时间:2024/05/16 04:48
  1. Find All Numbers Disappeared in an Array Add to List
    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]

方法一:未注意到即是使用系统自带的函数sort(),仍然会造成时间复杂度超出O(n),因为通常排序算法的时间复杂度都是大于等于O(nlogn)

vector<int> findDisappearedNumbers(vector<int>& nums) {        int len = nums.size();        if(len<=1)        {            return (vector<int> ());        }        sort(nums.begin(),nums.end());        int lowOne = 0;        int lowTwo = 1;        vector<int> result;        while(lowTwo < len)        {            if(nums[lowTwo] - nums[lowOne] <= 1)            {                lowOne++;                lowTwo++;            }            else            {                int temp = nums[lowTwo] - nums[lowOne];                int i = 1;                while(i<temp)                {                    result.push_back(nums[lowOne]+i);                    i++;                }                lowOne++;                lowTwo++;            }        }        //针对[1,1,2,2]的这种case        if(nums[len-1] < len)        {            int temp = len - nums[len-1];            int i = 1;            while(i<=temp)            {                result.push_back(nums[len-1]+i);                i++;            }        }       return result;     }

方法二:交换

//注意不断的将错误位置上的数据不断的交换移动到本该属于其的位置上去,则重新遍历时,nums[i]!=i+1的数字即没有出现的数字    vector<int> findDisappearedNumbers(vector<int>& nums) {        int len = nums.size();        vector<int> result;        for(int i = 0; i < len; i++)        {            if(nums[i] == i+1)            {                continue;            }            else            {                while(nums[nums[i] - 1] != nums[i] )                {                    //int idx = nums[i] - 1;                    int temp = nums[nums[i] - 1];                    nums[nums[i] - 1] = nums[i];                    nums[i] = temp;                }            }        }        for(int i = 0; i < len; i++)        {            if(nums[i] != i+1)            {                result.push_back(i+1);            }        }        return result;    }
0 0
原创粉丝点击