【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
}
相关推荐
sheeta1998几秒前
LeetCode 每日一题笔记 日期:2025.04.06 题目:874. 模拟行走机器人
笔记·leetcode·机器人
XiYang-DING5 分钟前
【LeetCode】232. 用栈实现队列
算法·leetcode·职场和发展
人道领域6 分钟前
【LeetCode刷题日记】142.环形链表Ⅱ
算法·leetcode·链表
2301_8227032014 分钟前
开源鸿蒙跨平台Flutter开发:基因序列比对基础:Needleman-Wunsch 算法的 Dart 实现
算法·flutter·开源·鸿蒙
Book思议-15 分钟前
【数据结构】「树」专题:树、森林与二叉树遍历之间的关系+408真题
数据结构·算法·二叉树··森林
Fcy64825 分钟前
算法基础详解(4)双指针算法
开发语言·算法·双指针
zk_ken26 分钟前
优化图像拼接算法思路
算法
xwz小王子28 分钟前
Nature Communications从结构到功能:基于Kresling折纸的多模态微型机器人设计
人工智能·算法·机器人
luj_176828 分钟前
从R语言想起的,。。。
服务器·c语言·开发语言·经验分享·算法
计算机安禾37 分钟前
【数据结构与算法】第29篇:红黑树原理与C语言模拟
c语言·开发语言·数据结构·c++·算法·visual studio