Chuyển tới nội dung chính

[E] Summary Ranges

Đề bài

Cho một mảng số nguyên không trùng lặp đã được sắp xếp, trả về tất cả các đoạn liên tiếp trong mảng đó.

Ví dụ:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]

Constraints:

  • 0 <= nums.length <= 20
  • -231 <= nums[i] <= 231 - 1
  • All the values of nums are unique.
  • nums is sorted in ascending order.

Phân tích

Solution

Solution

class Solution {
public:
vector<string> summaryRanges(vector<int> &nums) {
vector<string> rs = {};
int n = nums.size();
int start = 0;
int end = 1;
while (end <= n) {
if (end == n || nums[end] > nums[end - 1] + 1) {
string num_start = to_string(nums[start]);
if (start == end - 1) {
rs.insert(rs.end(), num_start);
} else {
rs.insert(rs.end(), num_start + "->" + to_string(nums[end - 1]));
}
start = end;
}
end++;
}

return rs;
}
};