Given an array nums
of n
integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums
.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1] Output: [5,6]
Example 2:
Input: nums = [1,1] Output: [2]
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
就是想不到解法,看了答案也思考了一会儿才反应过来,哎。看了一下别人的思考过程,其实可以从最简单的O(n) extra space的想法,就是新建一个数组,如果这个数字存在就把它对应的下标记成1,否则是0。其实这个extra数组可以改成就用当前数组,就如果这个下标对应的数字存在,就把这个数字变成负的,否则是正的。
Runtime: 18 ms, faster than 39.75% of Java online submissions for Find All Numbers Disappeared in an Array.
Memory Usage: 66.6 MB, less than 56.11% of Java online submissions for Find All Numbers Disappeared in an Array.
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
nums[index] = -Math.abs(nums[index]);
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
result.add(i + 1);
}
}
return result;
}
}
看到好像还有个in place sort的做法,和这个思路挺像的,只是需要swap一下,但是没仔细看。以后有空再说吧。Loading...