程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode daily question (Python Implementation) 01- sum of two numbers

編輯:Python

from 2022.6.19 From the beginning to the end of the autumn move , I will update at least one question every day leetcode I understand this blog On , Stick it up as evidence .

1. Code implementation

class Solution:
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
hashmap = {
}
for index, num in enumerate(nums):
num2 = target - num
if num2 in hashmap:
return [hashmap[num2], index]
hashmap[num] = index
return None

2. Understanding and explanation

enumerate function : You can get the index and element of an iteratable object , Store elements and indexes in a dictionary , Every time calculation target-num, If this value is in the key Note that the sum of two numbers in the list is equal to target, Return two numbers and the subscript in the array .

3. Time and space complexity


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved