【Leetcode】18. 四数之和

【Leetcode】18. 四数之和

题目链接

【Leetcode】18. 四数之和

代码

go 复制代码
func fourSum(nums []int, target int) [][]int {
	sort.Ints(nums)
	ans := make([][]int, 0)
	n := len(nums)
	for i := 0; i < n-3; i++ {
		if i > 0 && nums[i] == nums[i-1] {
			continue
		}
		for j := i+1; j < n-2; j++ {
			if j > i+1 && nums[j] == nums[j-1] {
				continue
			}
			l, r := j+1, n-1
			for l < r {
				sum := nums[i] + nums[j] + nums[l] + nums[r]
				if sum == target {
					ans = append(ans, []int{nums[i], nums[j], nums[l], nums[r]})
					for l < r && nums[l] == nums[l+1] {
						l++
					} 
					for l < r && nums[r] == nums[r-1] {
						r--
					}
					l++
					r--
				}else if sum < target {
					l++
				}else if sum > target {
					r--
				}
			}
		}
	}
	return ans
}
相关推荐
洛水水12 分钟前
【力扣100题】22. 矩阵置零
算法·leetcode·矩阵
Liangwei Lin12 分钟前
LeetCode 78. 子集
数据结构·算法·leetcode
多加点辣也没关系25 分钟前
数据结构与算法|第二十四章:算法思维总结与实战
算法·代理模式
炽烈小老头31 分钟前
【每天学习一点算法 2026/05/11】排序链表
学习·算法·链表
wefg136 分钟前
一些零散的算法
c++·算法
khalil102039 分钟前
代码随想录算法训练营Day-48 单调栈02 | 42. 接雨水、84.柱状图中最大的矩形
数据结构·c++·算法·leetcode·单调栈·接雨水
Hcoco_me39 分钟前
Ai:Agent/ infra / 智驾 / 推广算法 题库
人工智能·深度学习·算法·自动驾驶·剪枝
项目申报小狂人39 分钟前
提出了一种带双向搜索的粒子群优化算法,一种基于双四元数运动优化的新型无人机3D路径规划方法及应用
算法·3d·无人机
驼同学.39 分钟前
牛客网面试TOP101 - Python算法学习指南
python·算法·面试
大大杰哥1 小时前
leetcode hot100(3)子串
c++·算法·leetcode