【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
}
相关推荐
手写码匠16 分钟前
华为云Flexus+DeepSeek征文|基于华为云Flexus X实例 + Dify + DeepSeek 构建企业级智能知识库问答系统实战
人工智能·深度学习·算法·aigc
吴可可12332 分钟前
Win7上开发CAD2004自定义实体全解析
c++·算法
YXXY31334 分钟前
二叉树中的深搜算法介绍
算法
zz345729811336 分钟前
C语言中字符串常量存储位置
c语言·开发语言·算法·青少年编程
noipp37 分钟前
推荐题目:洛谷 P16510 [GKS 2015 #C] gRanks
java·c语言·开发语言·c++·python·算法
菜菜的顾清寒1 小时前
力扣HOT100(50)动态规划-零钱兑换
算法·leetcode·动态规划
周末也要写八哥1 小时前
三分钟读懂:如何解决做题数量不足的问题?
算法
8Qi81 小时前
LeetCode 148. 排序链表 —— 解法二:自底向上归并(迭代,O(1) 空间)
数据结构·算法·leetcode·链表·归并·迭代
凯瑟琳.奥古斯特1 小时前
力扣1235完整解法详解
java·开发语言·leetcode
嘿黑嘿呦1 小时前
数据结构-图论-最小生成树
数据结构·算法·图论