Question
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]
问题解析:
给定含有n个元素的数组,每个元素大小满足 1 ≤ a[i] ≤ n,找出其中缺少的元素。
Answer
Solution 1:
技巧性实现。
- 因为题目中说明了,要求在O(n)的时间复杂度和O(1)的空间复杂度上实现,且其中缺失的可能不止一个数字,所以与
LeetCode-268:Missing Number(寻找缺失数字)
解法有所不同。 - 这里利用一个技巧去实现。由题目可以知道,数组中的数字均满足1 ≤ a[i] ≤ n,也就是说其中的元素和数组的位置索引存在某种关联性。如果数组中不缺少数字,那么每一个元素就会与数组的位置索引所一一对应,那么我们就可以利用这种关系。
- 遍历数组,若元素存在
num[i]
,则将其看作位置索引,那么就把num[i]-1
位置上的元素变为负数。最终没有变为负数的元素所在的位置索引值,就是我们没有见过的数字。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
ArrayList<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++){
int value = Math.abs(nums[i])-1;
if (nums[value] > 0){
nums[value] = -nums[value];
}
}
for (int i = 0; i < nums.length; i++){
if (nums[i] > 0){
ret.add(i+1);
}
}
return ret;
}
}
- 时间复杂度:O(n),空间复杂度:O(1)