leetcode学习记录
leetcode学习记录二十
找到所有数组中消失的数字
难度:简单
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
本题两种方法,一种官方题解,另一种是在评论中看到的比较巧妙的方法,本质上都是标记数字中出现的数字,再一次循环将没出现过的加入list中
1.第一种用hashmap记录出现的数字
2.用数组中的数字做脚标,然后将该角标下的元素置为负,再一次循环找到大于零的元素即未修改过的元素的脚标
代码
//方法一 官方题解
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
HashMap<Integer, Boolean> hashTable = new HashMap<Integer, Boolean>();
// Add each of the numbers to the hash table
for (int i = 0; i < nums.length; i++) {
hashTable.put(nums[i], true);
}
// Response array that would contain the missing numbers
List<Integer> result = new LinkedList<Integer>();
// Iterate over the numbers from 1 to N and add all those
// that don't appear in the hash table.
for (int i = 1; i <= nums.length; i++) {
if (!hashTable.containsKey(i)) {
result.add(i);
}
}
return result;
}
}
//方法二
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
for (int i = 0; i < nums.length; i++){
nums[Math.abs(nums[i])-1] = -Math.abs(nums[Math.abs(nums[i])-1]);
}
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; ++i){
if (nums[i] > 0)
res.add(i+1);
}
return res;
}
}