Leetcode-448. Find All Numbers Disappeared in an Array-思路详解 - C++

48 篇文章 0 订阅
28 篇文章 0 订阅

题目

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~n直接,n为数组的大小)。一些元素出现了两次,一些元素出现了一次。

在数组中找1~n之间不存在的数。并返回。

要求:不适用额外的空间,且运行时间为O(n)。可以假设返回列表不作为额外的空间

思路解析

思路1

1,使用一个大小为len+1的数组,采用哈希思路。如果该数值存在,则将其计数值加一。
2,然后在从头遍历统计结果,如果第i处的值为0,则说明该值不存在。将其计入结果。
3,返回结果

总结:该算法使用了O(n)的空间,时间复杂度为O(n)。没有满足题目要求。

思路2

既然无法使用额外空间,那么就必须在原始数组上想办法。
由于题目的数据范围在1~n直接。采取交换策略,将数字i,放到第i个位置。
1,从前往后遍历数组
2,如果第i处的值等于i,则不用处理,因为它已经在自己的位置上了
3,如果不等于i。则将该值a[i]防止到第a[i]的位置。然后交换。如果需要交换的值为该值,则将需要交换的值,置为0。按照此方法把数组遍历一遍
4,然后遍历数组,如果第i个位置的值为0,则i为缺少的值。
5,判断数组是否为升序,如果为升序则结束,否则继续。

代码1

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int len = nums.size();
        vector<int> index_map(len+1,0);
        for(int i = 0; i < len; i ++){
            index_map[nums[i]]++;
        }
        vector<int> res;
        for(int i = 1;i <= len;i ++){
            if(index_map[i] == 0){
                res.push_back(i);
            }
        }
        return res;
    }
};

代码2

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int len = nums.size();
        while(!isUp(nums)){
            for(int i = 0;i < len; i++){
                //如果元素值不等于索引值,则交换到元素应该在的位置上
                if(nums[i] != 0 &&nums[i]-1 != i){
                    if(nums[nums[i] - 1] == nums[i] ){
                        nums[i] = 0;
                    }else{
                        int tmp = nums[nums[i]-1];
                        nums[nums[i]-1] = nums[i];
                        nums[i] = tmp; 
                    }
                }
            }
        }
        vector<int> res;
        for(int i = 0;i < len; i ++){
            if(nums[i] == 0){
                res.push_back(i+1);
            }
        }

        return res;
    }
    bool isUp(vector<int> &nums){
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] != 0 && nums[i] != i+1){
                return false;
            }
        }

        return true;
    }
};

总结

1,当题目中提出在原地或以空间复杂度O(1)解决问题时,可以从数据本身,出发。或者采取交换,等策略。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值