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]
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
while (nums[i] != -1 && i != nums[i] - 1) {
if (nums[i] == nums[nums[i] - 1]) {
nums[i] = -1;
break;
}
swap(nums[i], nums[nums[i] - 1]);
}
}
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == -1) {
result.push_back(i + 1);
}
}
return result;
}
};

本文介绍了一种高效查找数组中缺失元素的方法,该方法能够在O(n)的时间复杂度内完成,并且不使用额外的空间(忽略返回结果)。通过遍历数组并对元素进行置换,最终找出未出现在正确位置上的元素。
414

被折叠的 条评论
为什么被折叠?



