1 - Two Sum - python

80 阅读1分钟

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

AC code

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

        return []

如果使用指针来遍历数组中的元素进行查找会超出时间

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        
        if nums == []:
            return []
        
        if len(nums) == 1 and nums[0] != target:
            return []
        elif len(nums) == 1 and nums[0] == target:
            return [0]
        
       	p = 0
		cur = 1  
		while cur < len(nums):
   			if nums[p] + nums[cur] == target:
	           return [p, cur]
		   elif nums[p] + nums[cur] != target and cur == len(nums) - 1:
		       p += 1
		       cur = p + 1
		   else:
		       cur += 1
		
		return []

一种更省内存和运行时间的方法是利用python内置的数据结构map构建hashmap来存放数组中的元素,进而再进行后续的查找。

class Solution:
	def twoSum(self,nums,target):
		d = {}
		n = len(nums)
		for x in range(n):
			if target - nums[x] in d:
				return d[target-nums[x]],x
			else:
				d[nums[x]] = x