【LeetCode】448. Find All Numbers Disappeared in an Array

35 篇文章 0 订阅
26 篇文章 0 订阅

Problem:

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.

题目:给定一个n位数组,其中有些数最多出现两次,找出[1,n]中没有在数组中出现的数。

要求,不额外申请空间,且时间复杂度为O(n,其中申请存储返回值的list对象不计入额外申请空间。


思路:看题觉得数组内全为正数,可以将数值作为下标,数值为出现标志。但是不能申请额外空间,只能放弃申请数组和HashMap等,只能从题目允许的List上操作。

1. 先将数组排序,这个操作使用内置函数,复杂度应该...(解题时其实我忘考虑了)

2. 遍历数组,key为[1,n]中当前出现的数值,如果nums当前的值不等于key或者不比key大1,都视为数组值出现跳跃,缺少了一个或几个值

3. 遍历结束后,要考虑到缺少的数是否为[1,n]中最后几位。

代码:

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<>();
        int len = nums.length;
        if(len==0)
            return list;
        Arrays.sort(nums);
       
        int key = 0;
        for(int i = 0; i < len; i ++){
            if(nums[i]==key||nums[i]==(key+1))
                key=nums[i];
            else{
                key++;
                i--;
                list.add(key);
            }
                
        }
        key = nums[len-1];
        //也许缺少的数为最后几位
        while(key<len){
            key++;
            list.add(key);
            
        }
            
        return list;
    }

}

此题有毒,排名靠前的都不是遵守规则的解法,于是我也写了一个

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<>();
        int len = nums.length;
        if(len==0)
            return list;
        int[] arr = new int[len+1];
        for(int i=0;i<len;i++){
            arr[nums[i]]=1; 
        }
        for(int i=1;i<=len;i++)
        {
            if(arr[i]!=1)
                list.add(i);
        }                
        
            
        return list;
    }

}

轻轻松松....


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值