題目:
給定一個整數陣列nums和一個目標值target,請你在該陣列中找出和為目標值 的那兩個整數,并回傳他們的陣列下標,
你可以假設每種輸入只會對應一個答案,但是,你不能重復利用 這個陣列中同樣的元素,
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以回傳 [0, 1]
解法:
-
最優解法
1 class Solution: 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List(int) 5 :type target: int 6 :rtype List[int] 7 """ 8 9 temp_dict = {} 10 for i, num in enumerate(nums): 11 if target - num in temp_dict: 12 return [temp_dict[target - num], i] 13 14 temp_dict[num] = i # 不放在if陳述句前,為解決target-num=num的情況View Code
-
延伸知識點:
1、判斷key是否在dict中: key in c_dict 2、帶索引遍歷: for i,value in enumerate(c_list) 3、串列轉字典 c_dict = {} for i, value in enumerate(c_list): c_dict[i] = value 4、字典推導式 {value: key for key, value in c_dict.items()} 5、查看某個元素element在list中的index c_list.index(element) 6、通過pop移除并回傳某個元素(通過指定index) c_list.pop() # 默認index=-1,即移除并回傳最后1個元素 c_list.pop(1) # 移除并回傳第2個元素View Code
★★★ 如有問題,歡迎指正:[email protected] ★★★
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/73567.html
標籤:其他
下一篇:redis創建集群
