# 228. Summary Ranges

• Time: $O(n)$
• Space: $O(n)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public: vector summaryRanges(vector& nums) { vector ans; for (int i = 0; i < nums.size(); ++i) { const int begin = nums[i]; while (i + 1 < nums.size() && nums[i] == nums[i + 1] - 1) ++i; const int end = nums[i]; if (begin == end) ans.push_back(to_string(begin)); else ans.push_back(to_string(begin) + "->" + to_string(end)); } return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public List summaryRanges(int[] nums) { List ans = new ArrayList<>(); for (int i = 0; i < nums.length; ++i) { final int begin = nums[i]; while (i + 1 < nums.length && nums[i] == nums[i + 1] - 1) ++i; final int end = nums[i]; if (begin == end) ans.add("" + begin); else ans.add("" + begin + "->" + end); } return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans = [] i = 0 while i < len(nums): begin = nums[i] while i < len(nums) - 1 and nums[i] == nums[i + 1] - 1: i += 1 end = nums[i] if begin == end: ans.append(str(begin)) else: ans.append(str(begin) + "->" + str(end)) i += 1 return ans