美文网首页
Python 算法习题

Python 算法习题

作者: 天地会大中华区块链ceo | 来源:发表于2019-12-05 18:30 被阅读0次

给定一个整数数组nums和一个目标值target,请找出该target下的两个整数,并返回数组下标

def twoSum(nums,target):

    for i in range(len(nums)):  # 选取一个基数据,执行第一层遍历

        j = -1 # 添加一个判断指标

        if target - nums[i] in nums:

            if ((target - nums[i]) == nums[i]) & (nums.count(target - nums[i])==1):

                continue

            else:

                j = nums.index(target - nums[i])

                if i == j:

                    j = nums.index(target - nums[i], i+1)

                else:

                    break # break是终止最外层的for循环

        if j >0:

            return [i,j]

        else:

            return []

其中 j为最终结果的判定值,寻找对应的变量来反应返回结果的变化。

因为是遍历模式,其复杂度为o(n)

相关文章

网友评论

      本文标题:Python 算法习题

      本文链接:https://www.haomeiwen.com/subject/rcrjgctx.html