標籤:appear and example 位置 abs 目的 turned find 維數
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]
本題在一維數組中找到按順序缺失的數字 按照思維 首先最容易想到的是雜湊 那樣子的話 很容易得到重複的數字和缺失的數字 可是本題中不允許使用額外的空間
同時 如果簡單的使用雜湊 也並沒有應用到本題中題目的特性 本題題目中 一維數組大小為n 其中的數字也都是1~n的 其實這些數字減一即為數組的下標0~n-1
要好好利用數組中數字和數組下標的關係 在一次按照下標遍曆中 既可以按當前下標中的數字為下標 操作對應的數字 標定這個數字已經出現 多次出現 標定一次就好 當然 不同的標定也可以
就例子而言:從數組的第一個下表中的數字開始 4,找到其對應下表4-1:3, 數組中下標為3的地方標定一下 表示數組中(3+1)已經出現過了
當以這樣的方式標定為完整個數組時 那麼出現過的數字對應的下標的位置都被標定 沒出現過的即沒有被標定 遍曆一次就可以了
代碼:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
if (nums.size()==0)
return res;
for (int i=0; i<nums.size();++i)
{
int m=abs(nums[i])-1;
if (nums[m]>0)
nums[m] = -nums[m];
}
for (int i=0; i<nums.size();++i)
{
if (nums[i]>0)
res.push_back(i+1);
}
return res;
}
Find All Numbers Disappeared in an Array