LeetCode Algorithm

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014365862/article/details/84404763

刷lc不为其他,只为工程能力扩展与思维提升!

请看github:leetCode

 

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

# Runtime: 20 ms, faster than 100.00% of Python online submissions for Two Sum.
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        map = {}
        for i in range(len(nums)):
            if nums[i] not in map:
                map[target - nums[i]] = i
            else:
                return map[nums[i]], i

        return -1, -1

 

# Runtime: 1192 ms, faster than 33.33% of Python online submissions for Two Sum.
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            temp = target - nums[i]
            new_nums = nums[:i] + nums[i+1:]
            if temp in new_nums :
                j = new_nums.index(temp) + 1
                return [i, j]
        return [] 

 

展开阅读全文

没有更多推荐了,返回首页