1. 程式人生 > >LeetCode-448. Find All Numbers Disappeared in an Array

LeetCode-448. 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.

Example:

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

Output:
[5,6]

這道題給了我們一個數組,陣列中的數字可能出現一次或兩次,讓我們找出[1, n]中沒有出現在該陣列中的數字。1 ≤ a[i] ≤ n (n = size of array)

對於位置為i的元素,我們把該元素調整到nums[i] - 1 位置上,有點排序的味道了,因為1 ≤ a[i] ≤ n的存在,O(N)
出現一次的一定在指定位置上,而出現兩次的佔據了沒有出現的元素的位置上,當然這個方法也可以應用到442. Find All Duplicates in an Array

然後我們再去遍歷該陣列,不在指定位置上的元素就是沒有存在的元素了。

package solutions._448;

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

/**
 * 448. Find All Numbers Disappeared in an Array
 */
class Solution {

    private void swap(int[] arr, int i, int j) {
        if (i != j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

    public
List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> result = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[i] != nums[nums[i] - 1]) { swap(nums, i, nums[i] - 1); i--; } } for (int i = 0; i < nums.length; i++) { if (i + 1 != nums[i]) { result.add(i + 1); } } return result; } public static void main(String[] args) { Solution solution = new Solution(); int[] arr = {4, 3, 2, 7, 8, 2, 3, 1}; List<Integer> list = solution.findDisappearedNumbers(arr); System.out.println(Arrays.toString(arr)); System.out.println(list); } }