【leetcode初级】9-两数之和

2018-07-26  本文已影响15人  小流

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums_copy = []
        for i in nums:
            nums_copy.append(i)
        nums.sort()
        i = 0
        j = len(nums) - 1
        while i < j:
            if nums[i] + nums[j] == target:
                break
            elif nums[i] + nums[j] > target:
                j -= 1
            else:
                i += 1
        result = []
        for k,v in enumerate(nums_copy):
            if v == nums[i] or v==nums[j]:
                result.append(k)
        return result
上一篇下一篇

猜你喜欢

热点阅读