当前位置:网站首页>[算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
[算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
2022-07-06 09:18:00 【邓嘉文Jarvan】
[算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
题目1:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a ,b ,c ,使得 a + b + c = 0 ?请找出所有和为 0 且 不重复 的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1fGaJU
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1:
//思路: 双指针
//首先将数组排序
//固定一个数字nums[i],其他2个数字的和为-nums[i]即可,就是一个双指针问题
//去重,i,j遇到重复的数字就跳过就能去重
代码
func threeSum(nums []int) [][]int {
//思路: 双指针
//首先将数组排序
//固定一个数字nums[i],其他2个数字的和为-nums[i]即可,就是一个双指针问题
//去重,i,j遇到重复的数字就跳过就能去重
res := make([][]int,0)
//参数处理
if len(nums) < 3 {
return res
}
//排序
sort.Slice(nums,func(i,j int) bool{
return nums[i] < nums[j]
})
//固定一个数字 nums[i]
for i := 0; i < len(nums) -2 ; {
//双指针
j,k := i+1,len(nums) -1
for j < k {
temp := nums[i] + nums[j] + nums[k]
if temp == 0 {
res = append(res,[]int{
nums[i],nums[j],nums[k]})
//去重
jVal := nums[j]
for j < k && jVal == nums[j]{
j ++
}
}else if temp < 0 {
j ++
}else {
k --
}
}
//去重
iVal := nums[i]
for i < len(nums) && iVal == nums[i]{
i ++
}
}
return res
}
测试
边栏推荐
- It has been solved by personal practice: MySQL row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT
- [offer78]合并多个有序链表
- Lock wait timeout exceeded try restarting transaction
- Solution to the problem of automatic login in Yanshan University Campus Network
- The master of double non planning left the real estate company and became a programmer with an annual salary of 25W. There are too many life choices at the age of 25
- MySQL replacement field part content
- [Yu Yue education] guide business reference materials of Wuxi Vocational and Technical College of Commerce
- Lean product development - Lean Software Development & lean product development
- KF UD分解之伪代码实现进阶篇【2】
- Gravure sans fil Bluetooth sur micro - ordinateur à puce unique
猜你喜欢
随机推荐
Solution to the problem of automatic login in Yanshan University Campus Network
Lean product development - Lean Software Development & lean product development
【无标题】
2021.11.10汇编考试
wsl常用命令
FairyGUI摇杆
Unity3D,阿里云服务器,平台配置
HCIP Day 12
Game 280 weekly
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
Easy to use shortcut keys in idea
Remember an experience of ECS being blown up by passwords - closing a small black house, changing passwords, and changing ports
Fairygui joystick
Fairygui loop list
FairyGUI增益BUFF数值改变的显示
数据库课程设计:高校教务管理系统(含代码)
MySQL error warning: a long semaphore wait
Knowledge system of digital IT practitioners | software development methods -- agile
ORA-02030: can only select from fixed tables/views
idea问题记录









