Skip to content

Commit cd931f6

Browse files
add 228
1 parent 45a2ee2 commit cd931f6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,5 +207,39 @@ fun rotate(nums: IntArray, k: Int) {
207207
}
208208
}
209209

210+
/**
211+
* 228. Summary Ranges
212+
*/
213+
214+
fun summaryRanges(nums: IntArray): List<String> {
215+
val result = mutableListOf<String>()
216+
if (nums.isEmpty()) return result
217+
218+
var start = nums[0]
219+
var prev = nums[0]
220+
221+
for (i in 1 until nums.size) {
222+
if (nums[i] == prev + 1) {
223+
prev = nums[i]
224+
} else {
225+
if (start == prev) {
226+
result.add("$start")
227+
} else {
228+
result.add("$start->$prev")
229+
}
230+
start = nums[i]
231+
prev = nums[i]
232+
}
233+
}
234+
235+
// Add the last range
236+
if (start == prev) {
237+
result.add("$start")
238+
} else {
239+
result.add("$start->$prev")
240+
}
241+
242+
return result
243+
}
210244

211245

0 commit comments

Comments
 (0)