【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
}
相关推荐
t198751281 分钟前
基于因子图与和积算法的MATLAB实现
开发语言·算法·matlab
le serein —f3 分钟前
用go实现-回文链表
算法·leetcode·golang
rit84324997 分钟前
MFOCUSS算法MATLAB实现:稀疏信号重构
算法·matlab·重构
发疯幼稚鬼8 分钟前
散列及其分离链接法
c语言·数据结构·算法·链表·散列表
Bdygsl9 分钟前
数字图像处理总结 Day 1
人工智能·算法·计算机视觉
北郭guo10 分钟前
垃圾回收底层原理【深入了解】
java·jvm·算法
小年糕是糕手10 分钟前
【C++同步练习】C++入门
开发语言·数据结构·c++·算法·pdf·github·排序算法
报错小能手11 分钟前
数据结构 链式队列
数据结构·算法
Octhexis12 分钟前
LC191 位1的个数
算法
LDG_AGI25 分钟前
【推荐系统】深度学习训练框架(六):PyTorch DDP(DistributedDataParallel)数据并行分布式深度学习原理
人工智能·pytorch·分布式·python·深度学习·算法·spark