Description:
https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> result; for (int i = 0; i < nums.size();i++) { if (nums[i]!= i+1) { while (nums[nums[i] - 1] != nums[i]) swap(nums[i], nums[nums[i] - 1]); } } for (int i = 0; i < nums.size();i++) { if (nums[i]!= i+1) result.push_back(i+1); } return result; } }; |
Code for fastest algorithm:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int>result; for (int i = 0; i < nums.size(); i++) { int n = abs(nums[i]) - 1; nums[n] = nums[n] > 0 ? -nums[n] : nums[n]; } for (int i = 0; i < nums.size(); i++) { if (nums[i] > 0) result.push_back(i + 1); } return result; } }; |
Time & Space:
O(n) & O(1)