题目
给定一个范围在 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) {
int n = nums.length;
for (int num : nums) {
int x = (num - 1) % n;
nums[x] += n;
}
List<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (nums[i] <= n) {
ret.add(i + 1);
}
}
return ret;
}
}
大佬题解
思路
遍历每个元素,对索引进行标记
- 将对应索引位置的值变为负数;
遍历下索引,看看哪些索引位置上的数不是负数的。
- 位置上不是负数的索引,对应的元素就是不存在的。
由于数组的元素不存在0,所以也就不用考虑0乘以-1的情况了。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
//用来存放结果
List<Integer> res = new ArrayList<>();
//1. 遍历下数组的元素,对对应的索引位置的元素作标记
int len = nums.length;
for(int i = 0; i < len; i++){
int num = Math.abs(nums[i]); //由于数组的元素有可能被*-1,所以取绝对值
int index = num - 1;
if(nums[index] > 0){
nums[index] *= -1;
}
}
// 寻找没有标记的索引位置
for(int i = 0; i < len; i++){
if(nums[i] > 0){
int num = i + 1; //将索引转化为对应的元素
res.add(num);
}
}
return res;
}
}
类似双指针的解法
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
// 从低到高排序
Arrays.sort(nums);
// 看作一个1,2,3...自增列表,当前值=索引值+1
List<Integer> lList = new LinkedList<Integer>();
// 双指针
int index = 0;
for (int i = 0; i < nums.length;) {
// 正常元素:当前值=索引值+1,双指针同时移动
if (index + 1 == nums[i]) {
index++;
i++;
continue;
}
// 存在重复元素
if (index == nums[i]) {
i++;
continue;
}
// 存在缺省元素:慢指针开始追赶
lList.add(index + 1);
index++;
}
// 添加末尾缺省的元素
index++;
for (int i = index; i <= nums.length; i++) {
lList.add(i);
}
return lList;
}
}
标记法
创建一个大小为n的标记数组,遍历nums数组,记录符合条件的数字。
最后遍历标记数组,没被标记的即为未出现的数组。
本质上就是排序+去重
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>();
int len = nums.length;
int[] fz = new int[len];
//记录出现的数字
for(int t:nums) {
if(t>=1 && t<= len) {
if(fz[t-1]==0)
fz[t-1] = 1; //不为0表示出现过,即标记
}
}
for (int i = 0; i < len; i++) {
if(fz[i]==0) //未被标记的即未出现过
res.add(i+1);
}
return res;
}
}