[Algorithm] LeetCode 1. two numbers

LeetCode 1. two numbers (Python)

1, simple solution

The most simple two for loops Dafa:

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

But be careful not to write enumerate function, time out:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        size = len(nums)
        for i, m in enumerate(nums):
            j = i+1
            while j < size :
                if nums[i] + nums[j] == target:
                    return [i, j]
                else:
                    j+=1

2, using in optimization (again for loop?)

python Dafa is good: use in the method, you only need a for loop will be able to solve the problem (but in fact, the python in to help us do a loop to find)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            if target-nums[i] in nums:
                if i != nums.index(target-nums[i]):
                    return [i, nums.index(target-nums[i])]

3, (thinking algorithm hash table) with a python dictionary

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = {}
        for i in range(len(nums)):
            a = target - nums[i]
            if nums[i] in d:
                return d[nums[i]],i
            else:
                d[a] = i

Write to think to understand, value pairs in the dictionary d: Meaning {k v} is the k would make up the target position value in the range of nums v. (I.e., when nums [i] = k, nums [v] + num [i] = target.)
Edge of the note dictionary in the complementary position (value) complementary number (key) nums array required to traverse side, after the case to nums [i] when a record number of complementary = before is found, return to his position (value) and i is complete.

Guess you like

Origin www.cnblogs.com/importGPX/p/11263450.html