原题链接在这里: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:
public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if(nums == null || nums.length == 0){
return res;
} for(int i = 0; i<nums.length; i++){
int index = Math.abs(nums[i])-1;
if(nums[index] > 0){
nums[index] = -nums[index];
}
} for(int i = 0; i<nums.length; i++){
if(nums[i] > 0){
res.add(i+1);
}
} return res;
}
}
也可以把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:
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
for(int i = 0; i<nums.length; i++){
if(nums[i]-1>=0 && nums[i]-1<nums.length && nums[i]!=nums[nums[i]-1]){
swap(nums, i, nums[i]-1);
i--;
}
} for(int i = 0; i<nums.length; i++){
if(nums[i] != i+1){
res.add(i+1);
}
} return res;
} private void swap(int [] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
跟上Find All Duplicates in an Array, Find the Duplicate Number, Missing Number.