Find All Numbers Disappeared in an Array

weixin_33850890發表於2018-06-04

https://www.lintcode.com/problem/find-all-numbers-disappeared-in-an-array/description

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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
        Arrays.sort(nums);
        List<Integer> list = new ArrayList<>();
        if (nums[0] > 1) {
            list.add(1);
        }
        int max = nums.length;
        while (nums[nums.length - 1] < max) {
            list.add(max);
            max--;
        }
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            while (num - nums[i - 1] > 1) {
                list.add(num - 1);
                num--;
            }
        }
        return list;
    }
}

相關文章