【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
}
相关推荐
DoraBigHead1 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx2 小时前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior2 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者2 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7893 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价3 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七3 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战4 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说4 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
WebInfra4 小时前
如何在程序中嵌入有大量字符串的 HashMap
算法·设计模式·架构