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

[LeetCode] 448.Find All Numbers Disappeared in an Array

return htm put lis inpu pear rand ati n)

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]

這道題要求找出數組中消失的數據,我的解題思路是通過一個偽哈希表記錄存在的數據,然後再遍歷顯示沒有統計的。

    public static List<Integer> findDisappearedNumbers(int
[] nums) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); int[] ary = new int[nums.length+1]; for (int i = 0; i < nums.length; i++) { ary[nums[i]]++; } for (int i = 1; i < ary.length; i++) { if (ary[i] == 0) { arrayList.add(i); } }
return arrayList; }

更好的實現方案:http://www.cnblogs.com/grandyang/p/6222149.html

[LeetCode] 448.Find All Numbers Disappeared in an Array