两数之和

题目

给定一个整数数组 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. JZOJ5870 【NOIP2018模拟9.15】地图

    题目描述 Description

  2. day48作业

    使用Bootstrap框架编写一个简单的web静态页面 效果图: <!DOCTYPE html> <html lang="en"> <head> ...

  3. struts1 总结吧

    以前都是使用struts2,但是新公司要使用struts1,所有只有硬着头皮上了. 一.Dynamic Method Invoc : 自定义的 Action 必须继承 DispatchAction 而 ...

  4. select2下拉内容获取后台数据

    controller(id给select:text给另外的input框) @RequestMapping(value = "findUnit")public @ResponseBo ...

  5. nfs服务安装配置

    一.准备阶段 配置解析主机 检查版本及内核 二.服务端安装 1) 配置yum把下载好的软件留着,下次备用,不用再下载 cachedir=/var/cache/yum/$basearch/$releas ...

  6. 海量大数据大屏分析展示一步到位:DataWorks数据服务+MaxCompute Lightning对接DataV最佳实践

    1. 概述 数据服务(https://ds-cn-shanghai.data.aliyun.com) 是DataWorks产品家族的一员,提供了快速将数据表生成API的能力,通过可视化的向导,一分钟“ ...

  7. TZ_01MyBatis_SqlMapConfig.xml

    1.sqlMapConfig的配置 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE conf ...

  8. git(转)

    转载:http://www.cnblogs.com/my-freedom/p/5701427.html 一.如何安装git 下载地址: https://git-scm.com/download/win ...

  9. 2019-2-14-VisualStudio-通过外部调试方法快速调试库代码

    title author date CreateTime categories VisualStudio 通过外部调试方法快速调试库代码 lindexi 2019-2-14 22:1:37 +0800 ...

  10. npm ci命令比npm installer命令快2至10倍

    npm 5.7.1的发布给我们带了一系列新的功能. 其中我最喜欢的就是npm ci命令了. npm ci命令 1.npm ci命令只根据lock-file去下载node_modules. 如果你的pa ...