题解 | #两数之和#

两数之和

https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param numbers int整型一维数组
# @param target int整型
# @return int整型一维数组
#
class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        # refactor and sort the list
        sorted_numbers = [(idx, val) for idx, val in enumerate(numbers)]
        sorted_numbers.sort(key=lambda x: x[1])

        # find the cutpoint
        s = 0
        idx_1, idx_2 = 0, 1
        for i in range(len(sorted_numbers) - 1):
            s = sorted_numbers[i][1] + sorted_numbers[i + 1][1]
            if s >= target:
                idx_1, idx_2 = i, i + 1
                break

        # search bi-directional
        while True:
            s = sorted_numbers[idx_1][1] + sorted_numbers[idx_2][1]
            if s == target:
                break
            elif s > target:
                idx_1 -= 1
            else:
                idx_2 += 1

        # return the result
        res = [sorted_numbers[idx_1][0] + 1, sorted_numbers[idx_2][0] + 1]
        res.sort()
        return res

全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务