LeetCode.001.Two Sum, leetcode.001.two
Address: https://leetcode.com/problems/two-sum/
Question:
Given an array and a target, if the sum of two numbers in the array is exactly the same as the target, their subscript is returned.
Question:
There are a lot of ideas. You can simply do this by sorting them first, then traversing each number, and searching for the other in binary mode. Because python comes with a dictionary tree (dist ), this method is more convenient:
Create a table based on d = {value: subscript}, traverse each number, search for another one, and return the subscript of these two numbers.
Code:
1 class Solution (object): 2 def twoSum (self, nums, target): 3 "" 4: type nums: List [int] 5: type target: int 6: rtype: List [int] 7 "" 8 lena = len (nums) 9 d = {0x3fffffff: 0x3fffffff} 10 for I in range (lena ): 11 d [nums [I] = i12 13 for I in range (lena): 14 temp = target-nums [I] 15 if temp in d: 16 if d [temp]! = I: 17 return [I, d [temp]