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

LeetCode | 448. Find All Numbers Disappeared in an Array 数组技巧题

2018-02-04 15:29 197 查看
Givenan array of integers where 1 ≤ a[i] ≤ n (n =
size of array), some elements appear twice and othersappear once.
Findall the elements of [1, n] inclusive that do not appear inthis array.
Couldyou do it without extra space and in O(n) runtime? You may assume thereturned list does not count as extra space.
Example:

Input:

[4,3,2,7,8,2,3,1]

 

Output:

[5,6]

这一题和hard的第41题是一模一样的在我的博客里面也有,使用的方法也是一样的,保证能在O(n)的时间内计算出结果,

技巧就是使用nums[i]=0表示数字i+1出现过,之后只需要遍历一遍nums数组就能够得到哪几个数字是没有出现过的

class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> result; int tmp,l;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 0) continue;
tmp = nums[i];
while (nums[tmp - 1] != 0)
{
l = tmp;
tmp = nums[l - 1];
nums[l - 1] = 0;
}
}
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] != 0)
result.push_back(i+1);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: