Problem
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]
Solution
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua // Running time: 128 ms (beats 93.70%) class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { for (size_t i = 0; i != nums.size(); ++i) { int index = abs(nums[i]) - 1; if (nums[index] > 0) nums[index] *= -1; } vector<int> ans; for (size_t i = 0; i != nums.size(); ++i) if (nums[i] > 0) ans.push_back(i + 1); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment