题目描述:
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]
一个数组有n个数,每个数都在[1,n]的范围内,有的数出现一次,有的数出现两次,求1~n中没有出现的数,时间复杂度为O(n),不能用额外空间。由于数组元素大小的特殊性,可以令元素的值作为下一个元素的下标形成链表,依次遍历的时候对每个遍历到的元素做标记,而在数组中没有标记的元素的下标即为所求,那么要做标记同时保证不真正影响元素的值的最简单的方法就是取负数。
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
for(int i=0;i<nums.size();i++)
{
nums[abs(nums[i])-1]=-abs(nums[abs(nums[i])-1]);
}
vector<int> result;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>0) result.push_back(i+1);
}
return result;
}
};
本文介绍了一种高效查找数组中缺失数字的方法,利用O(n)时间复杂度和原地修改技术,避免了使用额外空间。通过将数组元素值作为索引来构建特殊的链表,并通过检查元素值的正负来确定哪些数字未出现。
438

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



