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 public class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> list = new ArrayList<Integer>(); 4 5 if (nums == null || nums.length == 0) return list; 6 7 for (int i = 0; i < nums.length; i++) { 8 int val = nums[i]; 9 if (nums[i] != -1) { 10 nums[i] = -1; 11 exchange(nums, val); 12 } 13 } 14 15 for (int i = 0; i < nums.length; i++) { 16 if (nums[i] == -1) { 17 list.add(i + 1); 18 } 19 } 20 return list; 21 } 22 23 public void exchange(int[] nums, int val) { 24 if (nums[val - 1] == val) return; 25 26 int temp = nums[val - 1]; 27 nums[val - 1] = val; 28 29 if (temp != -1) { 30 exchange(nums, temp); 31 } 32 } 33 }
1 public class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> list = new ArrayList<Integer>(); 4 5 if (nums == null || nums.length == 0) 6 return list; 7 8 for (int i = 0; i < nums.length; i++) { 9 int index = Math.abs(nums[i]) - 1; 10 if (nums[index] > 0) { 11 nums[index] = -nums[index]; 12 } 13 } 14 15 for (int i = 0; i < nums.length; i++) { 16 if (nums[i] > 0) { 17 list.add(i + 1); 18 } 19 } 20 return list; 21 } 22 }