python练习--两数之和

一.题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

二.示例:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

三.提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案

解题:用python中的list列表数据类型解决https://www.runoob.com/python/python-lists.html

解题关键:找到num2=target-num1的num2是否在也在list中,如果在,直接查找,如果不在,直接就结束

四.代码
解法一:

def twoSum(nums, target):
    lens = len(nums)
    j=-1 
    for i in range(lens):
        if (target - nums[i]) in nums:
            if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):
                continue
            else:
                j = nums.index(target - nums[i],i+1)             
                break
    if j>=0:
        return [i,j]
    else:
        return []
解法二(暴力破解)双层for循环:

```python
def twoSum(self, nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]

猜你喜欢

转载自blog.csdn.net/weixin_50888622/article/details/117483319