Find All Numbers Disappeared in an Array
2016-12-30 10:29
323 查看
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:
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 }
相关文章推荐
- LeetCode——Find All Numbers Disappeared in an Array
- [LeetCode] Find All Numbers Disappeared in an Array
- leetcode448 Find All Numbers Disappeared In An Array Java
- leetcode(448). Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array(leetcode)
- Leetcode448 Find All Numbers Disappeared in an Array
- leetcode解题报告(33): Find All Numbers Disappeared in an Array
- LC-Find All Numbers Disappeared in an Array
- leetcode_448 Find All Numbers Disappeared in an Array
- LeetCode Find All Numbers Disappeared in an Array
- leetcode-448-Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- LeetCode - 448 - Find All Numbers Disappeared in an Array
- [LeetCode]Find All Numbers Disappeared in an Array
- LeetCode 448 Find All Numbers Disappeared in an Array
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- LeetCode: Find All Numbers Disappeared in an Array
- LeetCode [448. Find All Numbers Disappeared in an Array] 难度[easy]
- LeetCode448 Find All Numbers Disappeared in an Array(java/python)
- leetcode 448 Find All Numbers Disappeared in an Array C++