【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
}
相关推荐
liujing102329291 小时前
Day09_刷题niuke20250609
java·c++·算法
不7夜宵1 小时前
力扣热题100 k个一组反转链表题解
算法·leetcode·链表
蒟蒻小袁2 小时前
力扣面试150题--课程表
算法·leetcode·面试
闻缺陷则喜何志丹2 小时前
【动态规划】B4336 [中山市赛 2023] 永别|普及+
c++·算法·动态规划·洛谷
不二狗3 小时前
每日算法 -【Swift 算法】电话号码字母组合
开发语言·算法·swift
AL流云。3 小时前
【优选算法】分治
数据结构·算法·leetcode·排序算法
C++ 老炮儿的技术栈9 小时前
UDP 与 TCP 的区别是什么?
开发语言·c++·windows·算法·visual studio
殇者知忧9 小时前
【论文笔记】若干矿井粉尘检测算法概述
深度学习·神经网络·算法·随机森林·机器学习·支持向量机·计算机视觉
mochensage11 小时前
C++信息学竞赛中常用函数的一般用法
java·c++·算法