【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
}
相关推荐
AI备案指南-满满19 分钟前
人工智能拟人化互动服务安全自评估报告的评估要点有哪些?
人工智能·算法·安全·机器人·大模型备案·算法备案
土司大王2 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
大熊背3 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander2583 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲4 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力554 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜4 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者4 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂4 小时前
leetcode 3622. 判断整除性 简单
leetcode
_Narcissus_5 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣