【一次过】Lintcode 1236. Find All Numbers Disappeared in an Array

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.

样例

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]


解题思路1:

很自然的想到用HashSet存储,然后在区间元素寻找是否在其中即可。时间O(n),空间O(n)。

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: return a list of integers
     */
    public List<Integer> findDisappearedNumbers(int[] nums) {
        // write your code here
        List<Integer> list = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        
        for(int num : nums)
            set.add(num);
        
        for(int i=1 ; i<=nums.length ; i++){
            if(!set.contains(i))
                list.add(i);
        }
        
        return list;
    }
}

解题思路2:

由于题目要求不能有额外空间,所以

标志位法:用正负标志位,区分出现的元素和未出现的元素

从左向右遍历数组arr,假设当前遍历到 arr 的第 i 个元素,用一个变量 j 记录 | arr[i] | - 1,访问arr 的第 j 个元素,如果该元素为正,则把它变为负;否则不变。

最后,遍历一遍数组,如果某个位置上的元素为正,说明该位置从来没有被访问过。

图中,arr[4] 和 arr[5]上的值为正,表示5(5 = 4 +1)、6(6 = 5+1)从未在arr中出现过。

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: return a list of integers
     */
    public List<Integer> findDisappearedNumbers(int[] nums) {
        // write your code here
        List<Integer> res = new ArrayList<Integer>();
        
        for(int i = 0; i < nums.length; i++) {
            int val = Math.abs(nums[i]) - 1;
            if(nums[val] > 0)
                nums[val] = -nums[val];
        }
        
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] > 0)
                res.add(i+1);
        }
        return res;
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值