leetcode.0001 two sum

leetcode.0001 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].

参考解答1(python3)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        nums_len = len(nums)
        for i in range(nums_len):
            if target-nums[i] in nums and i != nums.index(target-nums[i]):
                return i, nums.index(target-nums[i])

参考解答2(python3):

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        buffer_dict = {}; #Use a dictionary to store the valur target - nums[i],the time complexity is O(n)

        for i in range(len(nums)):
            if nums[i] in buffer_dict:
                return [buffer_dict[nums[i]], i];
            else:
                buffer_dict[target - nums[i]] = i;

猜你喜欢

转载自blog.csdn.net/qq_37954325/article/details/81076146
今日推荐