leetcode 228. Summary Ranges

 

You are given a sorted unique integer array nums.

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

 

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

Example 3:

Input: nums = []
Output: []

Example 4:

Input: nums = [-1]
Output: ["-1"]

Example 5:

Input: nums = [0]
Output: ["0"]

 

Constraints:

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

题目难度:简单题

C++代码:

 1 class Solution {
 2 public:
 3     vector<string> summaryRanges(vector<int>& nums) {
 4         vector<string> vec;
 5         string s;
 6         int j;
 7         // i指向连续range数组的第一个数,j一开始指向i下一个,如果一直是相邻的,则j一直往后移,直到j指向第一个不属于range数组的数。
 8         for (int i = 0; i < nums.size();) {
 9             j = i + 1;
10             while (j < nums.size()){
11                 if (nums[j - 1] + 1 != nums[j])
12                     break;
13                 ++j;
14             }
15             //这种情况表示i指向的range数组只有一个数。
16             if (j - i == 1) {
17                 s = to_string(nums[i]);
18             } else {
19                 s = to_string(nums[i]) + "->" + to_string(nums[j - 1]);
20             }
21             vec.push_back(s);
22             i = j; //i指向下一个range数组
23         }
24         return vec;
25     }
26 };

时间复杂度:$O(n)$


python3代码:

1 class Solution:
2     def summaryRanges(self, nums: List[int]) -> List[str]:
3         ranges = []
4         for n in nums:
5             if not ranges or n > ranges[-1][-1] + 1:
6                 ranges += [], // 最后的,很重要
7             ranges[-1][1:] = n, //最后的,很重要
8         return ['->'.join(map(str, r)) for r in ranges]

 

posted @ 2020-10-29 17:05  琴影  阅读(257)  评论(0编辑  收藏  举报