Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given
[0,1,2,4,5,7]
, return ["0->2","4->5","7"].
Solution:
We can use two pointers to record the start and the end of each range.
- class Solution {
- public:
- vector<string> summaryRanges(vector<int>& nums) {
- vector<string> result;
- int n = nums.size();
- if(n == 0)return result;
- if(n == 1){
- result.push_back(to_string(nums[0]));
- return result;
- }
- int start=nums[0];
- int end=nums[0];
- for(int i = 0; i < n;){
- while( i+1 < n && nums[i+1] == end + 1){
- end++;
- i++;
- }
- if(start != end){
- result.push_back(to_string(start) + "->" + to_string(end));
- }
- else{
- result.push_back(to_string(start));
- }
- i++;
- start = end = nums[i];
- }
- return result;
- }
- };
0 意見:
張貼留言