>[success] # 找到所有數組中消失的數字
* 題目描述
給你一個含 n 個整數的數組 nums ,其中 nums[i] 在區間 [1, n] 內。請你找出所有在 [1, n] 范圍內但沒有出現在 nums 中的數字,并以數組的形式返回結果。
* 示例 1:
輸入:nums = [4,3,2,7,8,2,3,1]
輸出:[5,6]
* 示例 2:
輸入:nums = [1,1]
輸出:[2]
?
* 提示:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
進階:你能在不使用額外空間且時間復雜度為 O(n) 的情況下解決這個問題嗎? 你可以假定返回的數組不算在額外空間內。
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array
>[danger] ##### 第一次解題思路
題目中規則是長度為`n` 且數組中值只包含在`[1,n]`,因此可以使用原地修改數組方法,將出現值所映射的腳標對應的值取反即可,如果該值已經為負數說明出現過一次則不取反,最后只要統計所有為正數的index 即為沒出現的值
* js 代碼
~~~
var findDisappearedNumbers = function(nums) {
// 將數組值所映射對應角標的值 取反
nums.forEach((cur) => {
const index = Math.abs(cur) - 1
if (nums[index] > 0) {
nums[index] *= -1
}
return cur
})
// 如果是正數說明該值沒出現過
return nums.reduce((acc, cur, index) => {
if (cur > 0) acc.push(index + 1)
return acc
}, [])
};
~~~


>[info] ## 題解
* 使用 **加n** 方法
1. 獲取當前值,以該值作為腳標獲取對應數組映射值
2. 將映射值進行 **+n** 其中n 為當前**數組長度**

注:在不停加n 過程中想獲取對應的映射值不能在單純的只是以當前值做數組下標,而是要通過取余形式即 **(num-1) % n**,有個小知識點 **(值)取余(取余值) 值 < 取余值** 取余結果為**值** 例如`6%8 = 6`
>[danger] ##### js
~~~
/**
* @param {number[]} nums
* @return {number[]}
*/
var findDisappearedNumbers = function(nums) {
// 將對應值映射作為腳標所映射值加數組長度
const {length} = nums
nums.forEach(num => {
// 獲取當前值映射key
const idx = (num-1) % length
nums[idx] += length
})
return nums.reduce((acc, cur, index) => {
// 小于當前數組長度的都是符合的
if(cur <= length){
acc.push( index + 1 )
}
return acc
},[])
};
~~~
>[danger] ##### java
~~~
import java.util.List;
import java.util.ArrayList;
public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int len = nums.length;
List<Integer> ls = new ArrayList();
for(int i=0; i< len; i++){
// 獲取 當前值映射的對應index
int idx = (nums[i] - 1)%len;
nums[idx] += len;
}
// 找到所有小于 length 值
for(int i=0;i< len; i++){
if(nums[i] <= len) ls.add(i+1);
}
return ls;
}
}
~~~
>[danger] ##### 其他
* 先去重在依次去找
~~~
var findDisappearedNumbers = function(nums) {
const set = new Set(nums)
const {length} = nums
const ls = []
for(let i =length;i>0;i--){
if(!nums.includes(i)) ls.push(i)
}
return ls
};
~~~
>[success] # 總結
思路就是使用 數組值絕對和數組長度進行匹配,然后將當前項作為index 去改變映射項,最后找到沒有按照規則改變的值,即為不存在值
- 刷題準備
- 統計數組中元素出現次數
- Leetcode -- 442數組中重復的數據
- leetcode -- 448 找到所有數組中消失的數字
- 字符類似題
- Leetcode -- 1002 查找共用字符
- Leetcode -- 1370上升下降字符串
- 指針類題解
- Leetcode -- 283 移動零
- Leetcode -- 26. 刪除有序數組中的重復項
- Leetcode -- 80. 刪除有序數組中的重復項 II
- Leetcode -- 27. 移除元素
- Leetcode -- 344. 反轉字符串
- Leetcode -- 125 驗證回文串
- Leetcode -- 11 盛最多水的容器
- Leetcode -- 1480. 一維數組的動態和