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"].
代码要求对数组中的元素进行分段。
首先给出字符串格式化函数,假设begin==end, 则输出字符串“begin”, 否则输出“begin->end”,代码例如以下:
string format(int begin, int end){char buffer[32];if (end == begin){sprintf(buffer, "%d", begin);}else{sprintf(buffer, "%d->%d", begin, end);}return string(buffer);}
然后对数组进行分段。代码例如以下:
vector summaryRanges(vector& nums) {vector result;if (nums.size()<1)return result;int begin, end;begin = end = nums[0];for (int i=1; i