【leetcode】1. 两数之和

leetcode 2019-02-19 2456 字 1079 浏览 点赞

题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

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

链接:https://leetcode-cn.com/problems/two-sum/


第一种:

class Solution(object):
    """
    执行用时: 10660 ms, 在Two Sum的Python3提交中击败了1.79% 的用户
    内存消耗: 7.2 MB, 在Two Sum的Python3提交中击败了98.66% 的用户
    """
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # 暴力穷举
        for n, i in enumerate(nums):
            for m, j in enumerate(nums):
                if n == m:
                    continue
                elif i+j == target:
                    return [n, m]
                else:
                    continue

第二种:

class Solution(object):
    """
    执行用时: 44 ms, 在Two Sum的Python3提交中击败了99.77% 的用户
    内存消耗: 7.2 MB, 在Two Sum的Python3提交中击败了97.36% 的用户
    """
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtyp
        """
        numsDup = nums.copy()
        numsDup.sort()  # 以升序排序

        l, r = 0, len(numsDup)-1  # 左右两根指针
        while l < r:
            leftNum = numsDup[l]
            rightNum = numsDup[r]

            if leftNum+rightNum > target:
                r -= 1
            elif leftNum+rightNum < target:
                l += 1
            else:
                # 当左右两个数相同时,先取第一个值的索引,然后删除
                # 再取第二个值的索引+1
                if leftNum == rightNum:
                    index = nums.index(leftNum)
                    nums.pop(index)
                    return [index, nums.index(rightNum)+1]
                else:
                    return [nums.index(leftNum), nums.index(rightNum)]

第三种:

class Solution(object):
    """
    执行用时: 44 ms, 在Two Sum的Python3提交中击败了99.77% 的用户
    内存消耗: 7.7 MB, 在Two Sum的Python3提交中击败了53.94% 的用户
    """
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtyp
        """
        # 用hashSet记录查询过的数字,如果存在两个元素之和等于target,
        # 遍历到第二个元素时程序才会返回结果
        hashSet = set()
        for n, i in enumerate(nums):
            if target-i in hashSet:
                return [nums.index(target-i), n]
            hashSet.add(i)


本文由 Guan 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论