iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 24
0
Software Development

刷刷題 or Alan Becker's game 製作 is a question 系列 第 24

目前做過最有趣的一題 : 26. Remove Duplicates from Sorted Array

  • 分享至 

  • xImage
  •  

26. Remove Duplicates from Sorted Array

tags: 刷題

題目: 26. Remove Duplicates from Sorted Array

Level: Easy

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

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

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

注解: 沒看到最後,腦衝下去做,就會頭痛...

Code

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        cnt = 0 
        for i in range(len(nums)):
            if i > 0:
                if nums[i-1]!=nums[i]:
                    cnt+=1
                    nums[cnt] = nums[i] # 這行超神奇...
                    
        print(cnt)
        print(nums)
        #for z in range(cnt+1):
        #    print(nums[z])
        return cnt+1

Result:
世界越快(看題fu來時) 心則慢(先不要直接Co)


上一篇
(Hard) 25. Reverse Nodes in k-Group
下一篇
(Easy) 27. Remove Element
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言