forked from WenchaoD/LeetCode_Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SummaryRanges.swift
31 lines (28 loc) · 875 Bytes
/
SummaryRanges.swift
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
/**
* Question Link: https://leetcode.com/problems/summary-ranges/
* Primary idea: Traverse the array and build string when num[i] != num[i - 1] + 1,
* note to handle the edge case when it goes to the end of the array
*
* Time Complexity: O(n), Space Complexity: O(n)
*/
class SummaryRanges {
func summaryRanges(nums: [Int]) -> [String] {
var res = [String]()
var str = ""
var start = 0
guard nums.count > 0 else {
return res
}
for i in 0 ... nums.count {
if i == nums.count || (i > 0 && nums[i] != nums[i - 1] + 1) {
str = "\(nums[start])"
if i - 1 != start {
str += "->\(nums[i - 1])"
}
res.append(str)
start = i
}
}
return res
}
}