【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
}
相关推荐
C雨后彩虹7 分钟前
无向图染色
java·数据结构·算法·华为·面试
坚持就完事了14 分钟前
扫描线算法
算法
鱼跃鹰飞17 分钟前
Leetcode尊享面试100题:252. 会议室
算法·leetcode·面试
程序员-King.18 分钟前
二分查找——算法总结与教学指南
数据结构·算法
Zevalin爱灰灰19 分钟前
现代控制理论——第三章 线性控制系统的能控性和能观性
线性代数·算法·现代控制
kklovecode21 分钟前
C语言之头文件,宏和条件编译
c语言·开发语言·算法
Xの哲學32 分钟前
Linux自旋锁深度解析: 从设计思想到实战应用
linux·服务器·网络·数据结构·算法
晚风吹长发36 分钟前
深入理解Linux中用户缓冲区,文件系统及inode
linux·运维·算法·链接·缓冲区·inode
程序员-King.44 分钟前
day131—链表—反转链表Ⅱ(区域反转)(LeetCode-92)
leetcode·链表·贪心算法
cwplh1 小时前
DP 优化一:单调队列优化 DP
算法