[py]letcode第一题求和

letcode第一题, tm的不好弄. 想了很久想到了一个粗蠢的解决办法.

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

第一次: 没考虑到值相同时

class getIndex():
    def getSum(self, nums, target):
        for i in nums:
            for j in nums:
                if i + j == target:
                    return nums.index(i),nums.index(j)


s = getIndex()
s = s.getSum([3, 2, 4], 6)
print(s)

写了三四遍, 写成了这样,不过被accept了.

class Solution:
    def twoSum(self, nums, target):
        d = {}
        # 将arr搞成字典
        for k, v in enumerate(nums):
            d[k] = v

        for i in nums:
            # 计算target的另一半
            tmp = target - i
            # 如果i移出去了, 另一半还在, 求另一半的索引
            arr = list(d.values())
            arr.remove(i)
            if tmp in arr:
                index1 = nums.index(i)
                index2 = arr.index(tmp) + 1
                return index1, index2
            if tmp in d.values() and nums.index(i) != nums.index(tmp):
                return nums.index(i), nums.index(tmp)


s = Solution()
# s = s.twoSum([3, 2, 3], 6)
# s = s.twoSum([3, 3], 6)
s = s.twoSum([2, 5, 5, 11], 10)
print(s)

别人更优雅的解决办法

这就是距离啊

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hash_map = {}
        for index, value in enumerate(nums):
            hash_map[value] = index
        for index1, value in enumerate(nums):
            if target - value in hash_map:
                index2 = hash_map[target - value]
                if index1 != index2:
                    return [index1 + 1, index2 + 1]
posted @ 2018-01-29 20:56  mmaotai  阅读(230)  评论(0编辑  收藏  举报