448. Find All Numbers Disappeared in an Array

题目摘要
给定一个整形数组,其中1≤a[i]≤n(n为数组长度),一些元素出现两次一些元素只出现一次,找到1~n中所有没有出现的元素。请用O(n)的时间复杂度,并且不使用额外的空间。

解法
1. 遍历数组元素,将n[n[i] - 1]置负,再遍历一次,如果n[i]不为负,则i + 1没有出现。
2. 遍历数组元素,对于每一个元素,如果n[i] != i + 1 && n[n[i] - 1] != n[i]则调换n[i]n[n[i] - 1]直到上述条件成立,再遍历一次,如果n[i] != i + 1i + 1没有出现

注意

可问问题

原题
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]

Solution#1

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<>();
        if (nums == null || nums.length == 0) return list;
        Arrays.sort(nums);
        for (int i = 1; i < nums[0]; i++) {
            list.add(i);
        }
        for (int i = 0; i < nums.length - 1; i++) {
            while (nums[i] < nums[i + 1] - 1) {
                list.add(++nums[i]);
            }
        }
        for (int i = nums[nums.length - 1] + 1; i <= nums.length; i++) {
            list.add(i);
        }
        return list;
    }
}

Solution#2

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List list = new ArrayList<Integer>();
        if (nums == null || nums.length == 0) return list;
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] != i + 1 && nums[nums[i] - 1] != nums[i]) {
                int tmp = nums[i];
                nums[i] = nums[tmp - 1];
                nums[tmp - 1] = tmp;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                list.add(i + 1);
            }
        }
        return list;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值