题目
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
代码模板:
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
}
}
分析
首先新定一个数组,然后把数字放到数组的index里面,然后再循环这个新数组,如果为0的话,就是缺失的index,把index+1放入list里面。
解答
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new ArrayList<>();
int [] newNums = new int [nums.length];
for(int i = 0;i<nums.length;i++){
newNums[nums[i]-1] = nums[i];
}
for(int j = 0;j<newNums.length;j++){
if(newNums[j] == 0){
result.add(j+1);
}
}
return result;
}
}

412

被折叠的 条评论
为什么被折叠?



