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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zpalyq110/article/details/86302031

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) runtime? You may assume the returned list does not count as extra space.
Difficulty:Easy
Example:

Input: [4,3,2,7,8,2,3,1]
Output: [5,6]

方法1:额外空间,不符合题目要求

  • Time complexity : O ( n ) O\left ( n \right )
  • Space complexity : O ( n ) O\left ( n \right )
    思路
    第一直觉就是建标志数组,出现过的标记为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 : O ( n ) O\left ( n \right )
  • Space complexity : O ( 1 ) O\left ( 1 \right )
    思路
    利用改变元素正负号和取绝对值的方法,取代新建标志数组
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;       
    }
};

猜你喜欢

转载自blog.csdn.net/zpalyq110/article/details/86302031
今日推荐