力扣1. Two Sum 两数之和 (python)

这篇博客介绍了LeetCode中的1号问题——两数之和。给定一个整数数组和一个目标值,需要找出数组中两个数的下标,使得它们相加等于目标值。文章提供了双循环的解题思路,但指出其时间复杂度较高,然后详细讲解了使用哈希表优化后的解决方案,将时间复杂度降低到O(n)。并给出了具体的Python代码实现。
摘要由CSDN通过智能技术生成

Leetcode 1. Two Sum 两数之和 (python)

题目

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.


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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

例子

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

思路

第一个思路是双循环解题,即在每个元素上都遍历一次整个数组,求是否有符合条件的另一元素。但是这样算法复杂度将会是 O ( n 2 ) O(n^2) O

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值