【leetcode每日刷题】18. 4Sum

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
package main
import(
	"sort"
	"fmt"
)
func fourSum(nums []int, target int) [][]int {
	var result [][]int
	if(len(nums) < 4){
		return result
	}
	sort.Ints(nums)
	for i := 0; i < len(nums); i++ {
		if i > 0 && nums[i] == nums[i-1] {
			continue
		}
		for j := i + 1; j < len(nums); j++ {
			if j > i+1 && nums[j] == nums[j-1] {
				continue
			}
			k := j + 1
			l := len(nums) - 1
			for k < l {
				sum := nums[i] + nums[j] + nums[k] + nums[l]
				if sum == target {
					result = append(result, []int{nums[i], nums[j], nums[k], nums[l]})
					k++
					for ; k < l && nums[k] == nums[k-1]; k++ {
					}
				} else if sum < target {
					k++
				} else {
					l--
				}
			}
		}
	}
	return result
}

func main(){
	nums := []int{1, 0, -1, 0, -2, 2}
	result := fourSum(nums, 0)
	fmt.Println(result)
}

采取遍历的方式:

1、首先判断数组中数据数量,少于4个直接返回

2、对数组中的元素进行排序

3、第一层循环i,遍历数组中的每一个元素,重复的相同元素直接跳过,第二层循环从i+1开始遍历数组中的每一个元素,重复元素跳过,第三层从j+1开始,同时和第四个数一起遍历,第四个数从数组的末尾开始向前遍历,终止条件是第三个数的索引小于第四个数,并将四个数相加,与target的大小进行比较,相等则加入到result中,小于target第三个数的索引向后,大于target则第四个数的索引向前移动。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值