给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例:
输入: [4,3,2,7,8,2,3,1]
输出: [5,6]
这里涉及到了统计数组中出现过的数字,而且不能使用额外的空间。
考虑使用传入的数组本身来标记出现过的数字,这里给出现过的数字取负值来实现标记的功能。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
for(int i=0;i<nums.length;i++){
int newIndex = Math.abs(nums[i]) - 1;
if(nums[newIndex]>0){
nums[newIndex]= nums[newIndex]*-1;}
}
List<Integer> result = new LinkedList<Integer>();
for(int i=0;i<nums.length;i++){
if(nums[i]>0){
result.add(i+1);
}
}
return result;
}
}
代码中的Math.abs的作用是取绝对值返回
需要注意的是这里的+1,-1的问题,因为数组的角标是从0开始计数的,但是数组的数字个数是从1开始计数的,所以需要从数字转换成角标要-1,从角标转换成数字要+1.
题解中还有使用哈希表来完成功能的办法。
我们假设数组大小为 N,它应该包含从 1 到 N 的数字。但是有些数字丢失了,我们要做的是记录我们在数组中遇到的数字。然后从
1⋯N1\cdots N1⋯N 检查哈希表中没有出现的数字。我们用一个简单的例子来帮助理解。算法:
我们用一个哈希表 hash 来记录我们在数组中遇到的数字。我们也可以用集合 set 来记录,因为我们并不关心数字出现的次数。
然后遍历给定数组的元素,插入到哈希表中,即使哈希表中已经存在某元素,再次插入了也会覆盖
现在我们知道了数组中存在那些数字,只需从 1⋯N1范围中找到缺失的数字。
从 1⋯N1 检查哈希表中是否存在,若不存在则添加到存放答案的数组中。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
// Hash table for keeping track of the numbers in the array
// Note that we can also use a set here since we are not
// really concerned with the frequency of numbers.
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;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/solution/zhao-dao-suo-you-shu-zu-zhong-xiao-shi-de-shu-zi-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。