LeetCode Solutions

228. Summary Ranges

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  vector<string> summaryRanges(vector<int>& nums) {
    vector<string> 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;
  }
};
			

class Solution {
  public List<String> summaryRanges(int[] nums) {
    List<String> 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;
  }
}
			

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