LeetCode: Summary Ranges Posted on January 10, 2018July 26, 2020 by braindenny Combine ranges Similar Problems: CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #groupelements, #manydetails Given a sorted integer array without duplicates, return the summary of its ranges. Example 1: Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Example 2: Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. // https://code.dennyzhang.com/summary-ranges // Basic Ideas: twopointer + simulation // // Complexity: Time O(n), Space O(1) func summaryRanges(nums []int) []string { res := []string{} // nums[i...j] i := 0 for j:=0; j<len(nums); j++ { if j+1<len(nums) && nums[j]+1 == nums[j+1] { continue } // last group or group ends if i==j { res = append(res, fmt.Sprintf("%d", nums[i])) } else { res = append(res, fmt.Sprintf("%d->%d", nums[i], nums[j])) } // need to start a new group i = j+1 } return res } // https://code.dennyzhang.com/summary-ranges // Basic Ideas: twopointer + simulation // // Complexity: Time O(n), Space O(1) func summaryRanges(nums []int) []string { res := []string{} // nums[i...j] i := 0 for j:=0; j<len(nums); j++ { if j == len(nums)-1 || nums[j]+1 != nums[j+1] { // last group or group ends if i==j { res = append(res, fmt.Sprintf("%d", nums[i])) } else { res = append(res, fmt.Sprintf("%d->%d", nums[i], nums[j])) } if nums[j]+1 != nums[j] { // need to start a new group i = j+1 } } } return res } ## https://code.dennyzhang.com/summary-ranges ## Basic Ideas: 2 pointer ## Complexity: Time O(n), Space O(1) ## Assumptions: class Solution(object): def summaryRanges(self, nums): """ :type nums: List[int] :rtype: List[str] """ res = [] length = len(nums) i=0 while i<length: j = i + 1 while j<length and nums[j] == nums[j-1] + 1: j += 1 if j != i+1: res.append("%d->%d" % (nums[i], nums[j-1])) else: res.append("%d" % nums[i]) i = j return res Post Views: 6