龙熠的技术小站

Leetcode 448 Find All Numbers Disappeared in an Array

从给定的乱序数字中找到最小到最大数之间空缺的数


题目

1
2
3
4
5
6
7
描述
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.
1
2
3
4
5
6
7
例子
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]

解题思路

先按照题目要求,数字不超过给定数列长度的前提,创建一个数列,按照1到N赋值

然后根据给定数列的数据,将刚才创建的数列中对应下标的数据变成0

排除0的数据,剩下的就是结果

解题

Language : swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
func findDisappearedNumbers(_ nums: [Int]) -> [Int] {
var newAr = [Int]()
if nums.count < 2{return newAr}
for i in 1...nums.count {
newAr.append(i)
}
for i in 0...nums.count-1 {
newAr[nums[i]-1] = 0
}
var returnAr = [Int]()
for i in 0...newAr.count-1{
if newAr[i] != 0 {
returnAr.append(newAr[i])
}
}
return returnAr;
}
}
分享