Leetcode第一题:两数之和

Leetcode第一题:两数之和

题目难度:简单

编程语言:Python

题目描述

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target的那两个整数,并返回它们的数组下标。
题目要求:
(1)你可以假设每种输入只会对应一个答案。
(2)数组中同一个元素在答案里不能重复出现。
(3)你可以按任意顺序返回答案。
题目实例:
在这里插入图片描述

解题思路

通过遍历数组下标寻找满足条件的数组元素,并且两个数组元素的下标不能相等,否则为同一个元素,第一个元素直接遍历整个数组,第二个元素从第一个元素的下一位开始遍历,可减少时间复杂度。

代码示例

(1)leetcode通过版

leetcode会直接用测试用例进行测试,因此不用调用函数。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        index = []
        for j in range(len(nums)):
            for k in range(j+1, len(nums)): 
                if nums[j]+nums[k] == target and j != k:
                    if len(index) >= 2:
                        break
                    else:
                        index.append(j)
                        index.append(k)
                        return index
                else:
                    continue
        return index
(2)Pycharm运行版

增加了输入数组和目标值的步骤,对函数进行调用。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        index = []
        for j in range(len(nums)):
            for k in range(len(nums)):
                if nums[j] + nums[k] == target and j != k:
                    if len(index) >= 2:
                        break
                    else:
                        index.append(j)
                        index.append(k)
                        print(index)
                        return index
                else:
                    continue
        print(index)


array = []
i = 0
while True:
    if i >= 3:
        break
    else:
        a = str(input("请输入整数:"))
        i += 1
        if not a.isdigit():
            print("输入不是整数,请重新输入")
            a = str(input("请输入整数:"))
            array.append(int(a))
        else:
            array.append(int(a))
print("输入数组为:", array)
# while True:
aimValue = str(input("请输入一个整数目标值:"))
if not aimValue.isdigit():
    print("目标值不是整数,请重新输入")
    b = input("请输入一个整数目标值:")
else:
    aimValue = int(aimValue)

solution = Solution()
solution.twoSum(nums=array, target=aimValue)

总结

查找时最好不要直接遍历元素,可以选择遍历元素下标,不然容易造成遍历出的两个值都是同一个下标的元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

willing秋刀鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值