iT邦幫忙

0

leetcode with python:26. Remove Duplicates from Sorted Array

  • 分享至 

  • xImage
  •  

題目:

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory

說真的一開始看到這題我完全看不懂它想表達什麼,後來才了解是要return這個陣列有幾個不同的數(k),同時把這些數按序移到陣列最前面
題目最後一行有說不能再開其他陣列,意即我們僅能在這個陣列上進行操作
ex:[0,0,1,1,1,2,2,3,3,4]==>return k=5 ,而此時的陣列為[0,1,2,3,4,,x,x,x,x] (x為任意值)

不過多虧input是sorted的陣列,讓整題容易許多

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k=1
        for i in range(len(nums)):
            if i+1<len(nums) and nums[i]!=nums[i+1]:
                nums[k]=nums[i+1]
                k=k+1
        return k

由於我們只要將陣列中的值各選一個做代表,移到前面k項,後面的值便可以隨意
因此當我們一偵測到前後值不一時,便表示出現了新的值(因為input是sorted list)
將遇到的新值往前面放,k代表了下次遇到新值要放的index,同時也能作為最後的回傳值(共有幾個相異值)
最後執行時間為93ms(faster than 88.54%)

那我們下題見


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

1 則留言

0
JohnWick
iT邦新手 5 級 ‧ 2022-06-22 22:30:42

題目真的長,閱讀障礙= =

我要留言

立即登入留言