228. Summary Ranges
Tags:
Medium
Skills:
Interval
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu bạn tóm tắt một mảng số nguyên đã được sắp xếp và không trùng lặp thành các đoạn liên tiếp. Mỗi đoạn liên tiếp được biểu diễn dưới dạng “a → b” nếu có nhiều hơn một phần tử, hoặc chỉ là “a” nếu chỉ có một phần tử
Approach
Ví dụ minh họa
Với input: [1][2][4][5][7]
Các đoạn liên tiếp là: [1][2], [4][5], [7]
Output: ["0->2","4->5","7"]
Time and space complexity
Solution
1function summaryRanges(nums: number[]): string[] {
2 const ranges: string[] = [];
3 let i = 0;
4 const n = nums.length;
5 while (i < n) {
6 let start = i;
7 while (i + 1 < n && nums[i + 1] === nums[i] + 1) {
8 i++
9 }
10
11 if (start === i) {
12 ranges.push(`${nums[i]}`)
13 } else {
14 ranges.push(`${nums[start]}->${nums[i]}`)
15 }
16 i++
17 }
18
19 return ranges
20};i dùng để duyệt qua mảngstart lưu lại chỉ số bắt đầu của đoạn liên tiếp