LeetCode 448. Find All Numbers Disappeared in an Array
原题链接在这里:https://leetcode.com/problems/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]
题解:
把nums[Math.abs(nums[i])-1]标负. 第二遍iterate 时若nums[i]非负,就表明原array没有i+1, 加到res中.
Time Complexity: O(nums.length). Space: O(1), regardless res.
AC Java:
1 public class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 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 res.add(i+1); 18 } 19 } 20 21 return res; 22 } 23 }
也可以把nums[i] swap到对应的index = nums[i]-1位置上.
第二遍iterate时,如果nums[i] != i+1. i+1就是disappeared, 加入res中.
Time Complexity: O(nums.length). Space: O(1), regardless res.
AC Java:
1 class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 for(int i = 0; i<nums.length; i++){ 5 if(nums[i]-1>=0 && nums[i]-1<nums.length && nums[i]!=nums[nums[i]-1]){ 6 swap(nums, i, nums[i]-1); 7 i--; 8 } 9 } 10 11 for(int i = 0; i<nums.length; i++){ 12 if(nums[i] != i+1){ 13 res.add(i+1); 14 } 15 } 16 17 return res; 18 } 19 20 private void swap(int [] nums, int i, int j){ 21 int temp = nums[i]; 22 nums[i] = nums[j]; 23 nums[j] = temp; 24 } 25 }
AC C++:
1 class Solution { 2 public: 3 vector<int> findDisappearedNumbers(vector<int>& nums) { 4 vector<int> res; 5 int len = nums.size(); 6 for(int i = 0; i < len; i++){ 7 if(nums[i] - 1 >= 0 && nums[i] - 1 < len && nums[i] != nums[nums[i] - 1]){ 8 swap(nums[i], nums[nums[i] - 1]); 9 i--; 10 } 11 } 12 13 for(int i = 0; i < len; i++){ 14 if(i + 1 != nums[i]){ 15 res.push_back(i + 1); 16 } 17 } 18 19 return res; 20 } 21 };
跟上Find All Duplicates in an Array, Find the Duplicate Number, Missing Number.