2023年5月30日 星期二

5/31 每日一題(數字範圍)

 You are given a sorted unique integer array nums.

range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

 

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

 

Constraints:

  • 0 <= nums.length <= 20
  • -231 <= nums[i] <= 231 - 1
  • All the values of nums are unique.
  • nums is sorted in ascending order.


class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        #找出連續數字的開始和結束
        result=[] #初始化空列表,紀錄範圍
        i=0 #首相開始,用來指向nums位置
        while i < len(nums): #遍歷nums

            start=nums[i] #範圍左端點            
            #右端點,從start開始,如果下一項超過1,就是自己一組
            end=start  #初始化左端點
            while i < (len(nums)-1 ) and nums[i+1] == nums[i] +1: 
            #檢查下一項是否連續
                end = nums[i+1] #更新右端點
                i+=1 #指針移動,直到超出定義範圍
            #確認指針是否開始與結束是否同
            if start == end:
                result.append(str(start))
            else:
                
                result.append(str(start)+"->"+str(end))
            i += 1  #從end的下一項進入下一圈
        return result