448. 找到所有数组中消失的数字
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
方法一 把出现过的数组索引对应的数组值变成相反数,如果为正数证明该索引+1的值未在数组中出现。
分析:
-
第一个数字是4,如果用nums[nums[0] - 1],就代表,选中第四个数(也就是7),然后对它取相反数。
-
以此类推,用一个循环完成nums[nums[i] - 1],就代表,选中第nums[i]个数字,然后取相反数。
-
按照本题输入,就是第4,3,2,7,8,1个数字变成相反数,也就是小于0的数字。
-
然后第二次循环遍历一次,第1个数字小于0,说明什么?说明原数组中一定有1,因此第一个数字才会被翻转,因此说明1出现过。然后2,3,4。
-
到5的时候,突然发现,哎?第五个数字(8)没被翻转,说明原数组里没有5出现过。以此类推。
AC代码:
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i])-1;
if(nums[index] > 0) {
nums[index] = - nums[index];
}
}
for(int j = 0; j < nums.length; j++) {
if(nums[j] > 0) {
list.add(j+1);
}
}
return list;
}
}
方法二 利用集合Set元素不可以重复特点
首先set也是Collection接口的子接口,即:
|---List
有序(存储顺序和获取顺序一致),可重复
|---Set
|---HashSet(通过HashCode和equals保证唯一性)
|---TreeSet(通过comparable的compareTo或者comparator的compare)
无序(存储顺序和获取顺序不一致),不可重复
AC code:
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++)
{
set.add(nums[i]);
}
for (int i = 1, count = 0; i <= nums.length; i++)
{
if (!set.contains(i))
{
res.add(i);
}
}
return res;
}
}