448. Find All Numbers Disappeared in an Array

题目链接:https://leetcode.com/problems...

一般这种类型的题要in place,要么给num[i]赋值成不在范围内的数,要么swap到对应位置。

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> result = new ArrayList();
        if(nums.length == 0) return result;
        // sign as negative when find a number
        for(int i = 0; i < nums.length; i++) {
            int index = Math.abs(nums[i]) - 1;
            nums[index] = -Math.abs(nums[index]);
        }
        // find positive number, whose index is not visited
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] > 0) result.add(i + 1);
        }
        return result;
    }
}

swap的方法见discussion:
https://discuss.leetcode.com/...

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> result = new ArrayList();
        if(nums.length == 0) return result;
        // swap to correct position
        for(int i = 0; i < nums.length; i++) {
            while(nums[i] != i + 1 && nums[i] != nums[nums[i] - 1]) {
                swap(nums, i, nums[i] - 1);
            }
        }
        // find positive number, whose index is not visited
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] != i + 1) result.add(i + 1);
        }
        return result;
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

lulouch13
13 声望6 粉丝