welcome to my blog
LeetCode Top 100 Liked Questions 448. Find All Numbers Disappeared in an Array (Java版; Easy)
题目描述
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
第一次做; 类似鸽巢原理的做法, 很巧妙; 看最下面的题解
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
ArrayList<Integer> res = new ArrayList<>();
if(nums==null || nums.length==0)
return res;
for(int i=0; i<nums.length; i++){
int index = Math.abs(nums[i])-1;
nums[index] = -Math.abs(nums[index]);
}
for(int i=0; i<nums.length; i++){
if(nums[i]>0)
res.add(i+1);
}
return res;
}
}
第一次做; 这道题的难点在于数组值和索引的对应关系相差1, 需要格外留意!
/*
鸽巢?
*/
import java.util.ArrayList;
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
ArrayList<Integer> res = new ArrayList<>();
if(nums==null || nums.length==0)
return res;
//
int index=0;
//尽可能让鸽子在正确的巢里
while(index<nums.length){
if(nums[index]==index+1){
index++;
}
//nums[index]!=index+1
else{
//如果nums[index]应该在的位置,已经有正确的元素了,count++
//值为value, 应该放在索引value-1处
if(nums[nums[index]-1]==nums[index]){
index++;
}
else{
swap(nums, index, nums[index]-1);
}
}
}
//统计哪些巢不正确
for(int i=0; i<nums.length; i++){
if(nums[i]!=i+1)
//添加的是i+1, 不是i!
res.add(i+1);
}
return res;
}
public void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
力扣优秀题解
核心思想:
原始数组:[4,3,2,7,8,2,3,1]
重置后为:[-4,-3,-2,-7,8,2,-3,-1]
比如说nums[0]==4, 就让nums[4-1] = - nums[4-1], 也就是让nums[3]=-nums[3], 只有4才能让索引3的值为负, 如果6没有出现过,那么索引5处的值还是整数, 这样通过查找哪个位置的数为正数,就知道是哪个值缺失了!
# 时间复杂度O(2n),空间复杂度 $O(1)$,res 不算额外空间
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# 将所有正数作为数组下标,置对应数组值为负值。那么,仍为正数的位置即为(未出现过)消失的数字。
# 举个例子:
# 原始数组:[4,3,2,7,8,2,3,1]
# 重置后为:[-4,-3,-2,-7,8,2,-3,-1]
# 比如说nums[0]==4, 就让nums[4-1] = - nums[4-1], 也就是让nums[3]=-nums[3], 只有4才能让索引3的值为负, 如果6没有出现过,那么索引5处的值还是整数, 这样通过查找哪个位置的数为正数,就知道是哪个值缺失了!
# 结论:[8,2] 分别对应的index为[5,6](消失的数字)
for num in nums:
index = abs(num) - 1
# 始终保持nums[index]为负数
nums[index] = -abs(nums[index])
return [i + 1 for i, num in enumerate(nums) if num > 0]
若将题目要求改为数组中每个元素出现的可能次数是n次,求出数组中出现次数为偶数(奇数)次的元素(出现 0 次也算偶数次)
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# 将所有正数作为数组下标,置对应数组值为相反数。那么,仍为正数的位置即为出现偶数次(未出现是0次,也是偶数次)数字。
# 举个例子:
# 原始数组:[1, 1, 1, 1, 2, 3, 4, 5]
# 重置后为:[1, -1, -1, -1, -2, 3, 4, 5]
# 结论:[1,3,5,6] 分别对应的index为[1,6,7,8](消失的数字)
for num in nums:
index = abs(num) - 1
# 保持nums[index]为相反数,唯一和上面的解法不同点就是这里,好好体会
nums[index] = -nums[index]
#偶数次
return [i + 1 for i, num in enumerate(nums) if num > 0]
#奇数次
return [i + 1 for i, num in enumerate(nums) if num < 0]