美文网首页
LeetCode 1 两数之和 (找到两个数之和等于特定数值)

LeetCode 1 两数之和 (找到两个数之和等于特定数值)

作者: _xuyue | 来源:发表于2019-08-21 15:14 被阅读0次

两数之和

题目大意

给定一个无序数组和一个目标值,要去从数组中选择两个数,使他们的和等于目标值。

题目思路

首先将列表排序。然后一头一尾开始遍历。由于最后返回的是数字在原数组中的下标,因此要创建一个列表,记录排序后的数组在原数组中的下标。

代码(Python3)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        indice = sorted(range(len(nums)), key=lambda k:nums[k])
        nums = sorted(nums)
        j = len(nums) - 1
        i = 0
        while(i<j):
            if nums[i] + nums[j] < target:
                i += 1
            elif nums[i] + nums[j] > target:
                j -= 1
            else:
                return [indice[i], indice[j]]

最后是题目的完整描述

题目描述

相关文章

网友评论

      本文标题:LeetCode 1 两数之和 (找到两个数之和等于特定数值)

      本文链接:https://www.haomeiwen.com/subject/fizbsctx.html