LeetCode : No1 Two Sum Python

来源:互联网 发布:js修改html属性值 编辑:程序博客网 时间:2024/05/17 20:35

题目链接:

https://leetcode.com/problems/two-sum/


考虑到效率问题,通过两层循环的方式,时间复杂度为O(n^2),时间溢出。


解法1:

利用python 自带的sorted排序,然后根据两数之和为target逐步从数组的两头向中间寻找,直到两数之后为target,再反定位数字在原数组的位置。


耗时:63ms


class Solution:    # @return a tuple, (index1, index2)    def twoSum(self, num, target):        sortedNum = sorted(num)        start = 0        end = len(sortedNum)-1        Sum = sortedNum[start]+sortedNum[end]        while  Sum != target:            if Sum > target:                end = end -1            else:                start = start +1            Sum = sortedNum[start]+sortedNum[end]        Min = num.index(sortedNum[start])        num[Min] = -float("inf")        Max = num.index(sortedNum[end])        if Min < Max:            return (Min+1,Max+1)        else:            return (Max+1,Min+1)





0 0