【leetcode】448. Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.web

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.app

Example:this

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

題目大意:

給定一個整數數組,其中1 ≤ a[i] ≤ n (n = 數組長度),一些元素出現兩次,其餘的出現一次。spa

尋找全部[1, n]中沒有出如今數組中的元素。code

能夠不使用額外空間並在O(n)運行時間求解嗎?你能夠假設返回列表不算額外空間。orm

解題思路:

正負號標記法blog

遍歷數組nums,記當前元素爲n,令nums[abs(n) - 1] = -abs(nums[abs(n) - 1])ci

再次遍歷nums,將正數對應的下標+1返回即爲答案,由於正數對應的元素沒有被上一步驟標記過。element

 1 class Solution {
 2 public:
 3     vector<int> findDisappearedNumbers(vector<int>& nums) {
 4         int len=nums.size();
 5         for(int i=0;i<len;i++)
 6         {
 7             int m=abs(nums[i])-1;
 8             nums[m]=nums[m]>0? -nums[m]:nums[m];
 9         }
10         vector<int>res;
11         for(int i=0;i<len;i++)
12             if(nums[i]>0)
13                 res.push_back(i+1);
14         return res;
15     }
16 };
相關文章
相關標籤/搜索