LEETCODE 1.Two Sum (python实现)

来源:互联网 发布:索尼z3sim网络解锁 编辑:程序博客网 时间:2024/06/06 00:58

题目:
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].

翻译:
给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。


 时间复杂度n^2

def twosum(nums, target):    for i in xrange(len(nums)):        for j in xrange(i+1, len(nums)):            if (nums[i] + nums[j]) == target:                return [i, j]

时间复杂度n(思考一下)

0 0
原创粉丝点击