448. 找到所有数组中消失的数字
题目:
给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。
思路:
遍历数组,将每个数字交换到它理应出现的位置上,下面情况不用换:
当前数字本就出现在理应的位置上,跳过,不用换。
当前数字理应出现的位置上,已经存在当前数字,跳过,不用换。
再次遍历,如果当前位置没对应正确的数,如上图索引 4、5,则将对应的 5、6 加入 res。
代码:
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
int i = 0;
//遍历数组,将每个数字交换到它理应出现的位置上
while (i < nums.length) {
//当前的数字就出现在它理应的位置上,不用换
if(nums[i] == i+1) {
i++;
continue;
}
int should = nums[i] - 1;
//当前的数字理应出现的位置上,已经存在当前数字,不用换
if(nums[i] == nums[should]) {
i++;
continue;
}
int temp = nums[i];
nums[i] = nums[should];
nums[should] = temp;
}
//再次遍历,如果当前位置不对应数字,则把当前位置的索引加入res
for (int j = 0; j < nums.length; j++) {
if (nums[j] != j + 1) {
res.add(j+1);
}
}
return res;
}
}
转载:
如有冒犯请私信我删除
链接:https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array/solution/shou-hua-tu-jie-jiao-huan-shu-zi-zai-ci-kzicg/