LeetCode 001 :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].


题目大意:

给定一个整数数组,从中找出两个数的下标,使得它们的和等于一个特定的数字。

可以假设题目有唯一解

测试用例如题目描述。

解题思路:

按顺序查找下一个是否符合要求


Python代码:



def Two_Sum(array,target):
    l=len(array)
    for i in range(l):
        for j in range(i,l):
            if i!=j:
                if array[i]+array[j]==target:
                    print('['+str(i)+','+str(j)+']')
arr=[2,7,64,23,4,5,6,56,56,3,2,4,6,2,1,5,6,2,23,546,6,4,3,23,1,5,11,15]
tar=9
Two_Sum(arr,tar)


猜你喜欢

转载自blog.csdn.net/qq1358223058/article/details/78018097