LeetCode-448. Find All Numbers Disappeared in an Array

来源:互联网 发布:上海php培训机构 编辑:程序博客网 时间:2024/06/16 02:58

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);    }}
阅读全文
0 0
原创粉丝点击