每日一题---18. 四数之和[力扣][Go]

又是仰望大佬的一天…

题目描述

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。

解题代码

失败(我写的)

// 会漏掉一部分示例
func fourSum(nums []int, target int) [][]int {
    
    
	// 先确定两边的指针再在两指针间利用双指针法进行遍历
	var res [][]int
	// 排序
	sort.Ints(nums)
	// 利用双指针法,先给两个指针固定位置
	n := len(nums)
	if n < 4 {
    
    
		return nil
	}
	fIndex := 0
	aIndex := n - 1
	for fIndex < aIndex-2 {
    
    
		num1 := nums[fIndex]
		num2 := nums[aIndex]
		lIndex := fIndex + 1
		rIndex := aIndex - 1
		for lIndex < rIndex {
    
    
			num3 := nums[lIndex]
			num4 := nums[rIndex]
			sum := num1 + num2 +num3  + num4
			if  sum == target{
    
    
				println(num1,num2,num3,num4)
				res = append(res, []int{
    
    num1,num2,num3,num4})
			}
			println("fIndex:",fIndex,",lIndex:",lIndex,",rIndex",rIndex,"aIndex",aIndex)
			if sum < target {
    
    
				lIndex ++
			} else {
    
    
				rIndex --
			}
			for nums[lIndex] == nums[lIndex - 1] && lIndex < rIndex {
    
    
				lIndex ++
			}
			for nums[rIndex] == nums[rIndex + 1] && lIndex < rIndex {
    
    
				rIndex --
			}
		}
		if num1 + num2 < 0{
    
    
			fIndex++
		} else {
    
    
			aIndex--
		}
		if fIndex != 0 {
    
    
			for nums[fIndex] == nums[fIndex - 1] && fIndex < aIndex-2 && fIndex != 0{
    
    
				fIndex ++
			}
		}
		if aIndex != n- 1 {
    
    
			for nums[aIndex] == nums[aIndex + 1] && fIndex < aIndex-2 && aIndex != n - 1{
    
    
				aIndex --
			}
		}

	}
	return res
}

成功(大佬写的)

func fourSum(nums []int, target int) [][]int {
    
    
	// 先确定前两个在将后面的元素利用双指针法遍历
	if len(nums) < 4 {
    
    
		return nil
	}
	sort.Ints(nums)
	var res [][]int
	for i := 0; i < len(nums)-3; i++ {
    
    
		n1 := nums[i]
		// if n1 > target { // 不能这样写,因为可能是负数
		// 	break
		// }
		// 跳过第一个重复的位置
		if i > 0 && n1 == nums[i-1] {
    
    
			continue
		}
		for j := i + 1; j < len(nums)-2; j++ {
    
    
			n2 := nums[j]
			// 跳过第二个重复的位置
			if j > i+1 && n2 == nums[j-1] {
    
    
				continue
			}
			l := j + 1
			r := len(nums) - 1
			// 双指针法
			for l < r {
    
    
				n3 := nums[l]
				n4 := nums[r]
				sum := n1 + n2 + n3 + n4
				if sum < target {
    
    
					l++
				} else if sum > target {
    
    
					r--
				} else {
    
    
					res = append(res, []int{
    
    n1, n2, n3, n4})
					for l < r && n3 == nums[l+1] {
    
     // 去重
						l++
					}
					for l < r && n4 == nums[r-1] {
    
     // 去重
						r--
					}
					// 找到答案时,双指针同时靠近
					r--
					l++
				}
			}
		}
	}
	return res
}

提交结果

在这里插入图片描述

おすすめ

転載: blog.csdn.net/weixin_52025712/article/details/121180150