LeetCode 448. Find All Numbers Disappeared in an Array
448. 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]
Subscribe to see which companies asked this question.
【题目分析】
给定一个整数数组,数组中的元素的值都大于1小于数组的长度,数组中某些元素存在重复值,找出那些1到之间缺失的值。要求时间复杂度为O(n),不使用额外的存储空间。
【思路】
1. 如果数组中不存在缺失值,即所有元素都只出现一次的话,每个下标就对应一个数。我们把数组中的数看作数组的下标,遍历数组,把当前元素与它作为下标对应位置的值交换位置,并把那个位置的值赋为0. 通过这个过程我们就知道了那些被找到的位置对应的元素是0,否则不为0. 把那些值不为0的下标返回即可。
2. The basic idea is that we iterate through the input array and mark elements as negative using nums[nums[i] -1] = -nums[nums[i]-1]
. In this way all the numbers that we have seen will be marked as negative. In the second iteration, if a value is not marked as negative, it implies we have never seen that index before, so just add it to the return list.
【java代码1】
1 public class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> res = new ArrayList<>(); 4 if(nums == null || nums.length == 0) return res; 5 6 for(int i = 0; i < nums.length; i++) { 7 if(nums[i] == 0 || nums[nums[i]-1] == 0) continue; 8 int temp = nums[i]-1; 9 nums[i--] = nums[temp]; 10 nums[temp] = 0; 11 } 12 13 for(int i = 0; i < nums.length; i++) { 14 if(nums[i] != 0) res.add(i+1); 15 } 16 17 return res; 18 } 19 }
【java代码2】
1 public class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> res = new ArrayList<>(); 4 if(nums == null || nums.length == 0) return res; 5 6 for(int i = 0; i < nums.length; i++) { 7 int val = Math.abs(nums[i]) - 1; 8 if(nums[val] > 0) nums[val] = -nums[val]; 9 } 10 11 for(int i = 0; i < nums.length; i++) { 12 if(nums[i] > 0) res.add(i+1); 13 } 14 15 return res; 16 } 17 }