您的位置:首页 > 移动开发

[LeetCode] Find All Numbers Disappeared in an Array

2017-02-16 21:33 501 查看
题目链接在此

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode