iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 11
0
自我挑戰組

Leetcode新手挑戰30天系列 第 11

#26 Remove Duplicates from Sorted Array

寫在開頭

今天挑題的方法是選#Easy和#Top Interview Questions
很好奇面試問題的類型都會是什麼樣的,就選了這題來試試看

進入正題

這次要做的題目如下~

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return 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 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]);
}

我理解到的意思是說,輸入是一個整數的陣列,輸出的長度是輸入陣列剔除重複元素的長度
比較特別的是,題目上說要避免使用其他新的空間來達成
不過我一開始想到的做法就是做一個新列表,挨個把沒有出現過的元素塞進新列表裡
像這樣:

def removeDuplicates(self, nums: List[int]) -> int:
    new_list = []
    for i in nums:
        if i in new_list:
            continue
        else:
            print(i)
            new_list.append(i)
    return len(new_list)

不使用其他空間的意思,題目下面也給了個參考,說用by reference的方式可以減少空間使用

BTW,寫code的時候突然有點搞混continue和pass,找到了參考1這篇說明,裡面有用break,continue,pass三種迴圈控制語法後的結果,很快就能看懂之間的差別!很有用!

參考資料

參考11 分鐘搞懂 Python 迴圈控制:break、continue、pass


上一篇
#136 Single Number - 試著自己解看看
下一篇
#26 Remove Duplicates from Sorted Array - 研究其他解法
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言