【LeetCode】448.Find All Numbers Disappeared in an Array
阿新 • • 發佈:2019-01-12
448.Find All Numbers Disappeared in an Array
Description:
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)
Difficulty:Easy
Example:
Input: [4,3,2,7,8,2,3,1]
Output: [5,6]
方法1:額外空間,不符合題目要求
- Time complexity :
- Space complexity :
思路:
第一直覺就是建標誌陣列,出現過的標記為1,最後結果是非1的索引
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n = nums.size();
vector<int> flag(n);
for (int i = 0; i < n; i++) {
flag[nums[i]-1] = 1;
}
vector<int> result;
for (int i = 0; i < n; i++) {
if (flag[i] != 1) {
result.push_back(i + 1);
}
}
return result;
}
};
方法2:最優解,符合題意
- Time complexity :
- Space complexity :
思路:
利用改變元素正負號和取絕對值的方法,取代新建標誌陣列
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
int pos = abs(nums[i]) - 1;
nums[pos] = nums[pos]>0 ? -nums[pos] : nums[pos];
}
vector<int> result;
for (int i = 0; i < n; i++) {
if (nums[i] > 0) {
result.push_back(i + 1);
}
}
return result;
}
};