problem 001

leetcode 001

Question

Two Sum

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.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

Answer

同样采用类似于冒泡排序的比较方法
对于使用python的一处结果感到好奇,方法a是先通过循环找出能够达到target的值 然后在通过index()来获取这两个值在原列表中的位置 方法b是每次循环时记录下index 找到达到target的值后直接保存当前的index
结果发现方法b反而比方法a慢2000ms
说明每次保存index的操作并不高效 大部分时候保存的都是无用的index

code
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums_copy=nums
        a=0
        b=0
        same_flag=0

        k_index=0
        l_index=1
        for k in nums_copy:#a_index
            l_s_index=k_index+1
            l_index=l_s_index
            for l in nums_copy[l_s_index:]:#b_index 
                if l+k == target:
                    a=k_index
                    b=l_index
                    break
                l_index+=1
            k_index+=1

        index0=a
        index1=b
        res=[]    
        if index0>index1 :
            res=[index1,index0]
        else :
            res=[index0,index1]
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值