1. consecutive to the previous, continue the loop
2. not consecutive to the previous, put string to the result, and i-- to reiterate the current element
I use an Integer length to mark how many numbers the string already has.
At the beginning, I use start and end index. But it makes the logics more complex.
Note: In for loop(line 7), only add s to result when checking the previous element is not continuous with the current one(Line 14). But for the last element of the array, no next element exists to do this judgement. So we have to add a judgement out of for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> result; int length=0; string s; for(int i=0; i<nums.size(); i++){ if(length == 0) { s.append(to_string(nums[i])); length++; continue; } //when consecutive if(nums[i]-nums[i-1] == 1){ length++; continue; } //when not consecutive if(length >1){ s.append("->"); s.append(to_string(nums[i-1])); } result.push_back(s); s.clear(); length=0; i--; } if(length==1) result.push_back(s); //when one single range at the end of vector nums if(length > 1) { s.append("->"); s.append(to_string(nums.back())); result.push_back(s); } return result; } }; |
Ugly codes. Need to optimize in the future.
Reference: http://blog.csdn.net/xudli/article/details/46645087
没有评论:
发表评论