题目如下:
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
自己的算法及代码如下:
- 首先定义一个 ArrayList,把原数组中的数字全部添加进去;
- 然后遍历 ArrayList,如果不包含 1-n 中的哪个数字,就将其添加到 ArrayList 的尾部;
- 最后删除之前的数组元素,List 中剩余的元素即为最终的返回值;
public class Solution {
public static List<Integer> findDisappearedNumbers(int[] nums) {
List numList = new ArrayList();
for (int i = 0; i < nums.length; i++){
numList.add(nums[i]);
}
for (int i = 1; i <= nums.length; i++){
if (!numList.contains(i)){
numList.add(i);
}
}
for (int i = 0; i < nums.length; i++){
numList.remove(0);
}
return numList;
}
public static void main(String[] args) {
int[] nums = new int[]{
4,3,2,7,8,2,3,1};
List result;
result = findDisappearedNumbers(nums);
System.out.println(result);
}
}
写完之后一运行正确,还觉得挺简单,然后提交的时候,就发现 超时了。。。
实在是想不出来再怎么改了,参考了一下其他的代码;
参考的的算法及代码如下:
分析:
- 把数组中的元素和索引建立一一对应的关系;
- 对数组中的每个元素对应的索引做个标记;
- 对索引进行一次遍历,那么不存在的元素就不会对它对应的索引进行比较,由此可以查找出不存在的元素;
思路:
- 遍历每个元素,对索引进行标记。将对应索引位置的值变为负数;
- 遍历索引,看哪些索引位置上的数不是负数。位置上不是负数的索引,对应元素就不存在;
public class Solution {
public static List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>();
//遍历数组元素,给对应的索引位置的元素作标记
for(int i = 0; i < nums.length; i++){
int num = Math.abs(nums[i]); //假定第 0 个元素为 4
int index = num - 1; //将元素4转换为下标,下标从0开始的话,它就是3
if(nums[index] > 0){
//数组的第3个数大于0(从0开始数)
nums[index] *= -1; //将第3个数变为负数
}
}
// 寻找没有标记的索引位置
for(int i = 0; i < nums.length; i++){
if(nums[i] > 0){
int num = i + 1; //将索引转化为对应的元素
res.add(num);
}
}
return res;
}
public static void main(String[] args) {
int[] nums = new int[]{
4,3,2,7,8,2,3,1};
List result;
result = findDisappearedNumbers(nums);
System.out.println(result);
}
}