題目鏈接在此
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]要求不用額外的空間,以及O(n)的時間。
額,這要求有點高啊。
不過有一個很重要的限制條件:1 ≤ a[i] ≤ n
于是大體思想就是:把數組中的每一個數(設為x),當做數組下標,把下標x處的數a[x]用其相反數-a[x]來代替。(當然,x要做下-1的處理,不然數組會越界)。
class Solution {public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> ans; for (int n : nums) { int val = abs(n) - 1; if(nums[val] > 0) nums[val] = -nums[val]; } for (int i = 0; i < nums.size(); i++) if (nums[i] > 0) ans.push_back(i + 1); return ans; }};
新聞熱點
疑難解答