leetcode 1. Two Sum排序+双指针

来源:互联网 发布:淘宝返现规定 编辑:程序博客网 时间:2024/05/18 13:44

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

python3的lambda排序方式

class Solution:    class Node(object):        def __init__(self, v, id):            self.v = v            self.id = id        def __lt__(self, other):            return  self.v < other.v    def twoSum(self, nums, target):        nodes = []        n = len(nums)        for i in range(0, n):            nodes.append(self.Node(nums[i], i))        nodes.sort()        l = 0;        r = n - 1        while l <= r:            sum = nodes[l].v + nodes[r].v            if sum == target:                return [nodes[l].id, nodes[r].id]            elif sum < target:                l += 1            elif sum > target:                r -= 1if __name__ == '__main__':    solve = Solution()    print(solve.twoSum([70, 2, 17, 11, 15], 19))