题目:
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"].
三指针。
C++版:
class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> results; if(nums.size() == 0) return results; if(nums.size() == 1) { string r = to_string(nums[0]); results.push_back(r); return results; } int i = 0, l = 0, r = 1; while(i < nums.size()) { while(r < nums.size() && nums[r] == nums[l] + 1) { l++; r++; } string re = to_string(nums[i]); if(l != i) { re += "->"; re += to_string(nums[l]); } results.push_back(re); i = r; l = r; r++; } return results; } };
public class Solution { public List<String> summaryRanges(int[] nums) { List<String> results = new ArrayList<>(); if(nums.length == 0) return results; if(nums.length == 1) { String s = new String(Integer.toString(nums[0])); results.add(s); return results; } int i = 0, l = 0, r = 1; while(i < nums.length) { while(r < nums.length && nums[r] == nums[l] + 1) { r++; l++; } StringBuffer s = new StringBuffer(Integer.toString(nums[i])); if(l != i) { s.append("->"); s.append(Integer.toString(nums[l])); } results.add(s.toString()); i = r; l = r; r++; } return results; } }
class Solution: # @param {integer[]} nums # @return {string[]} def summaryRanges(self, nums): results, l, r, i = [], 0, 1, 0 if len(nums) == 0: return results if len(nums) == 1: results.append(str(nums[0])) return results while i < len(nums): while r < len(nums) and nums[r] == nums[l] + 1: l += 1 r += 1 result = str(nums[i]) if l != i: result += "->" result += str(nums[l]) results.append(result) i = r l = i r += 1 return results