標籤:已耗用時間 length elements run ext other arraylist math 運行
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 ≤ a[i] ≤ n (n = 數組長度),一些元素出現兩次,其他的出現一次。
尋找所有[1, n]中沒有出現在數組中的元素。
可以不使用額外空間並在O(n)已耗用時間求解嗎?你可以假設返回列表不算額外空間。
思路:直接在原數組上遍曆。如果出現過,將其本來應該在的位置設定為負值。最後遍曆,為正的即為缺失值
1 public List<Integer> findDisappearedNumbers(int[] nums) { 2 List<Integer> result = new ArrayList<>(); 3 for (int i=0;i<nums.length;i++) 4 { 5 int val = Math.abs(nums[i]) - 1; 6 if(nums[val] > 0) { 7 nums[val] = -nums[val]; 8 } 9 }10 for(int i = 0; i < nums.length; i++) {11 if(nums[i] > 0) {12 result.add(i+1);13 }14 }15 return result; 16 }
448. Find All Numbers Disappeared in an Array