iT邦幫忙

1

leetcode with python:228. Summary Ranges

  • 分享至 

  • xImage
  •  

題目:

You are given a sorted unique integer array nums.

A 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

給定一個陣列,將裡面連續的整數依題目要求變為range表示後回傳
ex:input:[0,2,3,4,6,8,9]=>output:["0","2->4","6","8->9"]
explanation:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

這題我稍微採取了雙指標的概念實作

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        ans=[]
        i=0
        j=0
        while j<len(nums):
            if j<len(nums)-1 and nums[j+1]-nums[j]==1:
                j=j+1
            else:
                if i==j:
                    ans.append(str(nums[j]))
                    j=j+1
                    i=j
                else:
                    ans.append(str(nums[i])+"->"+str(nums[j]))
                    j=j+1
                    i=j
        return ans

兩指標都放在陣列之始(i,j)
假如下一項比前一項多1(即連續),j繼續往前
反之,則開始"結算"
若i和j位置不同,代表出現了range,起終點剛好是nums[i]和nums[j]
我們依題目要求append"nums[i]->nums[j]"
若i和j位置相同,代表沒有range,append"nums[j]"即可
如此判斷直到陣列尾端
特別注意j走到尾端時就一定要"結算"了
要特別做個條件式判斷
最後執行時間27ms(faster than 97.50%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言