LeetCode1——Two Sum

题目链接

暴力法

class Solution:
    def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
        for i in range(0, len(nums)-1):
            for j in range(i+1, len(nums)):
                if nums[i]+nums[j] == target:
                    return [i,j]

排序之后两端搜索

class Solution:
    def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
        new_num = sorted(nums)
        i = 0
        j = len(nums) - 1
        while i < j :
            if new_num[i]+new_num[j] == target:
                break
            if new_num[i]+new_num[j] < target:
                i = i + 1
            if new_num[i]+new_num[j] > target:
                j = j - 1

        for x in range(0, len(nums)):
            if nums[x] == new_num[i]:
                for y in range( 0, len(nums)):
                    if y == x:
                        continue
                    if nums[y] == new_num[j]:
                        if x > y :
                            return [y, x]
                        else:
                            return [x, y]

当然,暴力法的时间复杂度是n的平方,排序是nlogn,如果建立一个哈希表的话,应该会更快一点,毕竟底层实现不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值