【刷题-LeetCode】228. Summary Ranges
- Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
解 直接扫描
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string>ans;
int start = 0;
for(int i = 1; i <= nums.size(); ++i){
if(i == nums.size() || nums[i] != nums[i-1] + 1){
if(i == start+1){
ans.push_back(to_string(nums[start]));
}else{
ans.push_back(to_string(nums[start])+"->"+to_string(nums[i-1]));
}
start = i;
}
}
return ans;
}
};
作者:Vinson
-------------------------------------------
个性签名:只要想起一生中后悔的事,梅花便落满了南山
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!