两数之和

题目

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解答

1,爆破,O(N^2)

2,要找到任意 x + y = target,同等于 y = target - x,那么 把外层作为 x 遍历,查询 y 在不在列表即可,查询用哈希优化复杂度O(1)

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash_dict = {} for index, x in enumerate(nums):
y = target - x
if y in hash_dict:
return [hash_dict[y], index]
hash_dict[x] = index

三数之和

题目

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

解答

1,爆破,时间复杂度太高,O(N^3)。Time: O(N^3), Space: O(1)

def threeSum(self, nums):
# 爆破
pass

2,排序+双指针,外层遍历作为a,内层用双指针寻找b c,使得a+b+c=0。Time: O(N^2), Space: O(1)

具体思路如下:

标签:数组遍历
首先对数组进行排序,排序后固定一个数 nums[i]nums[i],再使用左右指针指向 nums[i]nums[i]后面的两端,数字分别为 nums[L]nums[L] 和 nums[R]nums[R],计算三个数的和 sumsum 判断是否满足为 00,满足则添加进结果集
如果 nums[i]nums[i]大于 00,则三数之和必然无法等于 00,结束循环
如果 nums[i]nums[i] == nums[i-1]nums[i−1],则说明该数字重复,会导致结果重复,所以应该跳过
当 sumsum == 00 时,nums[L]nums[L] == nums[L+1]nums[L+1] 则会导致结果重复,应该跳过,L++L++
当 sumsum == 00 时,nums[R]nums[R] == nums[R-1]nums[R−1] 则会导致结果重复,应该跳过,R--R−−
时间复杂度:O(n^2),n为数组长度
class Solution:
def threeSum(self, nums):
if not nums or len(nums) < 3:
return []
nums.sort() # 先排序
ans = [] lenth = len(nums)
for i in range(lenth): # 外层循环
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]: # 防止相邻i相同出现重复值,不要比较i和i+1,因为当前i和i+1也许会和其他一个数组成一个元祖
continue
L = i + 1
R = lenth - 1
while L < R:
sum = nums[i] + nums[L] + nums[R]
if sum < 0:
L += 1
elif sum > 0:
R -= 1
elif sum == 0:
ans.append([nums[i], nums[L], nums[R]]) # 找到
while L < R and nums[L] == nums[L + 1]: # 防止相邻L相同出现重复值
L += 1
while L < R and nums[R] == nums[R - 1]: # 防止相邻R相同出现重复值
R -= 1
L += 1 # 继续走
R -= 1
return ans

3,遍历外面两层a b,判断c在不在内层,内层用哈希表查找O(1)。Time: O(N^2), Space: O(N)

def threeSum(self, nums):
if len(nums) < 3:
return []
nums.sort()
ans = set() for i, a in enumerate(nums[:-2]):
if a > 0:
break
if i > 0 and a == nums[i-1]:
continue
hash_dict = {}
for b in nums[i+1:]:
if b not in hash_dict: # 把 c 加入哈希表
hash_dict[-(a+b)] = 1
else:
ans.add((a, -(a+b), b))
return map(list, ans)

【Leetcode】两数之和,三数之和,四数之和的更多相关文章

  1. 【leetcode 简单】第三题 回文数

    判断一个整数是否是回文数.回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数. 示例 1: 输入: 121 输出: true 示例 2: 输入: -121 输出: false 解释: 从左向 ...

  2. LeetCode:两数之和、三数之和、四数之和

    LeetCode:两数之和.三数之和.四数之和 多数之和问题,利用哈希集合减少时间复杂度以及多指针收缩窗口的巧妙解法 No.1 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在 ...

  3. [LintCode/LeetCode]——两数和、三数和、四数和

    LintCode有大部分题目来自LeetCode,但LeetCode比较卡,下面以LintCode为平台,简单介绍我AC的几个题目,并由此引出一些算法基础. 1)两数之和(two-sum) 题目编号: ...

  4. 【LeetCode】18、四数之和

    题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...

  5. 【算法训练营day7】LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和

    [算法训练营day7]LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和 LeetCode454. 四数相加I ...

  6. [LeetCode] 454. 4Sum II 四数之和II

    Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such t ...

  7. LeetCode:四数之和【18】

    LeetCode:四数之和[18] 题目描述 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c ...

  8. 【LeetCode】 454、四数之和 II

    题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...

  9. 【数据结构】Hash表简介及leetcode两数之和python实现

    文章目录 Hash表简介 基本思想 建立步骤 问题 Hash表实现 Hash函数构造 冲突处理方法 leetcode两数之和python实现 题目描述 基于Hash思想的实现 Hash表简介 基本思想 ...

  10. 【LeetCode】18.四数之和

    题目描述 18. 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 t ...

随机推荐

  1. css的其他相关样式属性

    一.颜色 1.预定义的表示颜色的单词 red,black.gray,pink...... 2.16进制表示 # + 6位16进制的数字0 1 2 3 4 5 6 7 8 9 a b c d e f 如 ...

  2. 计算机程序是怎么通过cpu,内存,硬盘运行起来的?

    虽然以前知道计算机里有CPU,内存,硬盘,显卡这么些东西,我还真不知道这些东西是怎么协作起来完成一段程序的,能写出程序却不懂程序,也不会向别人解释他们的关系,所以特意总结了一下,写的比较浅显,和我一样 ...

  3. Bash新技能

    1. 输出数组全部元素 echo ${array_name[@]} 2. 输出数组长度 echo ${#array_name[@]} #获得数组长度 echo ${#string_name} #获得字 ...

  4. PAT甲级——A1046 Shortest Distance

    The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed t ...

  5. IndentationError: expected an indented block错误

    Python语言是一款对缩进非常敏感的语言,给很多初学者带来了困惑,即便是很有经验的python程序员,也可能陷入陷阱当中.最常见的情况是tab和空格的混用会导致错误,或者缩进不对,而这是用肉眼无法分 ...

  6. 洛谷P2827 蚯蚓

    传送门 pts85/90(90应该是个意外,第一次交是90之后都是85了): 优先队列模拟题意 #include<iostream> #include<cstdio> #inc ...

  7. css3之弹性盒模型(Flex Box)

    CSS3 弹性盒子(Flex Box) 弹性盒子是 CSS3 的一种新的布局模式. CSS3 弹性盒( Flexible Box 或 flexbox),是一种当页面需要适应不同的屏幕大小以及设备类型时 ...

  8. ubuntn系统下将文件拷贝到优盘中及挂载概念理解

    参考资料:http://jingyan.baidu.com/article/7082dc1c76f178e40a89bdd3.html: http://bbs.csdn.net/topics/3801 ...

  9. sublime中用less实现css预编译

    实现css预编译的方式有很多,听说glup很流行而且功能也很强大,但是就目前的工作而言,仅要css预编译和YUIcompress就够了,接下来切入正题 Less 是一门 CSS 预处理语言,它扩展了 ...

  10. SpringBoot+Shiro+mybatis整合实战

    SpringBoot+Shiro+mybatis整合 1. 使用Springboot版本2.0.4 与shiro的版本 引入springboot和shiro依赖 <?xml version=&q ...