【記錄帖】(No.001)從零打卡刷Leetcode

2021-02-15 小詹學Python

點擊上方「小詹學Python」,選擇「置頂公眾號」

資源乾貨第一時間送達!

寫在前邊:

小詹一直覺得自己編程能力不強,想在網上刷題,又怕不能堅持。不知道有木有和小夥伴和小詹一樣想找個人一起刷題呢?歡迎和小詹一起定期刷leetcode,每周一周五更新一題,每一題都吃透,歡迎一題多解,尋找最優解!歡迎小夥伴們把自己的思路在留言區分享出來噢~

No.1 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.

題目大意:給出一個數字列表和一個目標值(target),假設列表中有且僅有兩個數相加等於目標值,我們要做的就是找到這兩個數,並返回他們的索引值。

例如:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

小詹第一反應就是兩層循環就可以解決,小case,的確思路簡單,但是時間複雜度,你懂得!很簡單就能想到的代碼如下:

def twoSum(self, nums, target):
   """
   :type nums: List[int]
   :type target: int
   :rtype: List[int]
   """
   result = []
   for i in range(len(nums)):
      for j in range(i+1, len(nums)):
          if nums[i] + nums[j] == target:
              result.append(i)
              result.append(j)
              return result

其實這裡也可以用一層循環即可實現,因為我們知道有且僅有一個解;我們可以通過判斷target與某一個元素的差值是否也在列表之中即可,這個和兩層循環思路類似,但是不難想到計算次數就下降了,代碼如下:

def twoSum(self, nums, target):
   """
   :type nums: List[int]
   :type target: int
   :rtype: List[int]
   """
   result = []
   for i in range(len(nums)):
      oneNum = nums[i]
      twoNum  = target - oneNum
      if twoNum in nums:
         j = nums.index(twoNum)
         if i != j:
            result.append(i)
            result.append(j)
            return result

的確兩種方案都輕鬆通過了,but用時過長,排名老靠後了。之後小詹在網上找到了另一種方案,整體思路和一層循環的方案二有點類似:通過創建字典,將nums裡的值和序號對應起來,並創建另一個字典存儲目標值(Target)-nums的值,通過判斷該值是否在nums內進行判斷並返回其對應索引值,代碼如下:

def twoSum(self, nums, target):
       """
       :type nums: List[int]
       :type target: int
       :rtype: List[int]
       """
       
       num_dict = {nums[i]:i for i in range(len(nums))}
       print(num_dict)
       
       num_dict2 = {i:target-nums[i] for i in range(len(nums))}
       print(num_dict2)
       
       result = []
       for i in range(len(nums)):
           j = num_dict.get(num_dict2.get(i))
           if (j is not None) and (j!=i):
               result = [i,j]
               break
       return result

該方案,在時間效率上還較為理想,小詹親測結果排名如下:

不知道小夥伴們能否提出更加節約時間的方案呢?如果有請聯繫小詹,在下一次打卡時候分享給大家!獨樂樂不如眾樂樂噢!

休息是為了走更遠的路

Python系列之——在北京當房奴的日子~

爬蟲和反反爬蟲(下篇)

歡迎並感謝土豪朋友們的打賞,一毛錢不嫌少,一百塊不嫌多哈哈~

相關焦點

  • leetcode刷題指南之Triangle
    int ans = dp[0];    for(int j = 1; j < lenr; j ++) {        ans = min(ans, dp[j]);    }    return ans;}};作者:東大ACM退役隊伍編輯:劉凱旋推薦閱讀:leetcode
  • leetcode刷題指南之PalindromePairs
    = i)25                    ans.push_back({ma[r], i});26            }27        }28        return ans;29    }30};作者:東大ACM退役隊伍編輯:劉凱旋推薦閱讀:leetcode刷題指南之
  • leetcode刷題指南之findtheduplicatenumber
    if (nums[i] <= m) cnt++;10        if (cnt > m) r = m;11        else l = m + 1;12    }13    return l;14}15};作者:東大ACM退役隊伍編輯:劉凱旋推薦閱讀:leetcode
  • 【小資料】Excelhome 3000資源帖下載(手慢無)
    李銳老師,盧子他們比我要講的細緻多了,還比我有耐心。那我就扒一些資料分享給大家吧!我開了一個【小資料】的專題,把幫助我成為高手的那些資料,陸續的分享給大家。好不好?沒錯,我把3000資源帖的連結,保存到了一個Excel表格裡,方便你篩選、搜索,看完之後,可以在旁邊做一個標記。
  • Leetcode weekly contest三月小結
    我一直建議大家分類刷題,這也意味著很多用遞歸DFS/BFS、哈希、查找、堆棧這些常規套路可以解決的題目,應該問題不大。並且在未來的某一個時刻f,燈泡j會被打開,也就是左邊的空缺都會被補上;所以,可以用一個set或者hashtable去記錄i+1左邊有哪些燈泡沒有打開(比如 missing_set),同時記錄下有哪些右邊的燈泡被提前打開了(比如 advance_set)。
  • 來刷 LeetCode 啊
    為什麼要刷LeetCode,刷LeetCode吃力正常嗎?
  • 程式設計師面試的刷題網站都在這了,想要的趕緊拿走!
    首先為什麼要刷題呢?
  • LeetCode 系列 19-20題
    P0019刷題地址: https
  • LeetCode刷題筆記(1)
    一個人的命運啊,不僅要考慮歷史的進程,還要考慮個人的努力,近期明顯懈怠下來的筆者決定開啟LeetCode刷題大業,從第一題開始按順序刷掉LeetCode
  • ​LeetCode刷題實戰46:全排列
    今天和大家聊的問題叫做 全排列,我們先來看題面:https://leetcode-cn.com/problems/permutations/Given a collection of distinct integers, return all possible permutations.
  • LeetCode-39.組合總和(Combination Sum)
    1 <= target <= 500來源:力扣(LeetCode)連結:https://leetcode-cn.com/problems/combination-sum/Link:https://leetcode.com/problems/combination-sum/DFS找到所有的答案,標準的DFS, 時間複雜度 = 答案個數
  • ​LeetCode刷題實戰72:編輯距離
    今天和大家聊的問題叫做 編輯距離,我們先來看題面:https://leetcode-cn.com/problems/edit-distanceGiven two words word1 and word2, find the minimum number of operations required to convert word1
  • ​LeetCode刷題實戰15題: 三數之和
    今天和大家聊的問題叫做三數之和 ,我們先來看題面:https://leetcode.com/problems/3sum/描述給定一個整數的數組,要求尋找當中所有的a,b,c三個數的組合,使得三個數的和為0.注意,即使數組當中的數有重複,同一個數也只能使用一次。
  • ​LeetCode刷題實戰148:排序鍊表
    今天和大家聊的問題叫做 排序鍊表,我們先來看題面:https://leetcode-cn.com/problems/sort-list/Given the head of a linked list, return the list after sorting it in ascending order.
  • ​LeetCode刷題實戰120: 三角形最小路徑和
    今天和大家聊的問題叫做 三角形最小路徑和,我們先來看題面:https://leetcode-cn.com/problems/triangle/Given a triangle, find the minimum path sum from top to bottom.
  • ​LeetCode刷題實戰16: 最接近的三數之和
    今天和大家聊的問題叫做最接近的三數之和 ,我們先來看題面:https://leetcode-cn.com/problems/3sum-closest/Given an array nums of n integers and an integer target, find three integers in nums such that
  • 刷題日記 | Search:LeetCode 39. Combination Sum
    >    cur.pop點擊閱讀原文可查看花花醬講解視頻環境轉碼小蟲子LeetCode萌新歡迎關注Bugword,我會不定期分享刷題日記