forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMissingRanges.swift
More file actions
43 lines (37 loc) · 1.18 KB
/
MissingRanges.swift
File metadata and controls
43 lines (37 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Question Link: https://leetcode.com/problems/missing-ranges/
* Primary idea: Scan the array and compare each element with previous one and generate corresponding ranges
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class MissingRanges {
func findMissingRanges(_ nums: [Int], _ lower: Int, _ upper: Int) -> [String] {
if nums.isEmpty {
return [getRange(lower - 1, upper + 1)]
}
var res = [String]()
for (i, num) in nums.enumerated() {
if i == 0 {
if lower < num {
res.append(getRange(lower - 1, num))
}
} else {
if nums[i - 1] + 1 < num {
res.append(getRange(nums[i - 1], num))
}
}
}
if nums.last! + 1 < upper + 1 {
res.append(getRange(nums.last!, upper + 1))
}
return res
}
private func getRange(_ numPrev: Int, _ numPost: Int) -> String {
if numPrev + 2 == numPost {
return "\(numPrev + 1)"
} else {
return "\(numPrev + 1)->\(numPost - 1)"
}
}
}