iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 1
0
自我挑戰組

Leetcode新手挑戰30天系列 第 1

#1 Two Sum

寫在開頭

第一次參加鐵人賽,也是第一次挑戰寫Leetcode題目。
滿緊張的,一開始想報名鐵人賽主題的時候突然想起同事A在離職前幾個月曾經跟我說過
https://ithelp.ithome.com.tw/upload/images/20190902/20113393LdJiUT5QAl.png
聽著特別熱血,但那時候我沒跟他一起寫。
直到最近腦袋充血,一頭熱的報名了鐵人賽。主要是想用最近學習的python語言來練習、補強下自己的演算法和資料結構的知識。總之這30天會記錄我自己解題的想法、查過的資料等等。

正題開始

Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

這題題目給了兩個輸入:一個整數陣列、一個目標整數;
要找出整數陣列中,哪兩個不相同的元素和會等於目標整數,並將這兩個元素索引值回傳。

我想到的做法是用巢狀迴圈的方式,用雙層迴圈去找符合條件的元素索引。

sudocode大概長這樣:
for (i=0, i<len(nums), i++)
for (j=i+1, j<len(nums), j++)
if nums[i] + nums[j] = target then
return i, j
end if
但python不這樣寫的,記得for loop語法是這樣:
for i in nums:
for j in range(i+1, len(nums)+1):
if nums[i] + nums[j] == target:
return i, j
最後在leetcode上run的code長這樣:

    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in nums:
            for j in range(i+1, len(nums)):
                if (nums[i] + nums[j] == target):
                    return i, j

但是測試結果總是失敗,應該有bug,因為找滿久的,就查了別人的解答:

    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            left = nums[i+1:]
            for j in range(len(left)):
                if (nums[i] + left[j]) == target:
                    return i, j+i+1

在第二個for迴圈的地方他使用反過來的方法做,但不曉得為什麼我的run過但答案不正確。
又回頭查了下自己的code,發現在if那句判斷應該這樣寫:
if (nums[i] + nums[j]) == target:
這樣run會成功, 測試也能過了!

另外還有找到其他種解法,晚點再來研究更好的方法。

參考資料

LeetCode (1) Two Sum (python)


下一篇
#1 Two Sum - 研究其他種解法
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
rtfgvb74125
iT邦新手 4 級 ‧ 2022-10-27 14:33:48

您的code還有些許bug,您的第一個迴圈的nums應該改成range(len(nums)),不然回傳的i值不會是位置而是字串當下的值。

我要留言

立即登入留言