给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
解法:
func findDisappearedNumbers(_ nums: [Int]) -> [Int] {
guard !nums.isEmpty else {
return []
}
var res = [Int]()
var nums = nums
for i in 0..<nums.count
{
//把出现过的元素 下标 标记为-1
if (nums[abs(nums[i]) - 1] > 0)
{
nums[abs(nums[i]) - 1] *= -1;
}
}
for i in 0..<nums.count
{
//将未出现的元素加入到数组中
if (nums[i] > 0)
{
res.append(i + 1);
}
}
return res;
}