LeetCode01: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].

LeetCode:链接

参考链接

暴力解法时间复杂度是O(n*n),不可以这么做。如果是有序的,用头指针和尾指针。如果是无序的,用字典的形式。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) < 2:
            return None
        my_dict = {}
        for i in range(len(nums)):
            if nums[i] not in my_dict:
                my_dict[target-nums[i]] = i
            else:
                return [my_dict[nums[i]], i]
        

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/82699929