• 每日一道:四数之和


    package main
    
    import (
    	"fmt"
    	"sort"
    )
    
    /*
    给定一个包含 n 个整数的数组 nums 和一个目标值 target,
    判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?
    找出所有满足条件且不重复的四元组。
    输入:nums = [1,0,-1,0,-2,2], target = 0
    输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
    */
    // N 数之和的本质是,在有序数组内,寻找 N 个数的和恰好是 S
    // 解决办法还是 3sum 3sum_closest 的双指针法,不过需要外部 N-2 层循环,内部双指针循环即可
    // 注意双指针在遍历时外部所有循环要去重,指针移动时也要去重
    func main() {
    	fmt.Println(fourSum([]int{1, 0, -1, 0, -2, 2}, 0)) // [[-2 -1 1 2] [-2 0 0 2] [-1 0 0 1]]
    }
    func fourSum(nums []int, target int) [][]int {
    	sort.Ints(nums)
    	n := len(nums)
    	var res [][]int
    	for i := 0; i < n-1; i++ {
    		if i > 0 && nums[i] == nums[i-1] {
    			continue
    		}
    		for j := i + 1; j < n; j++ {
    			if j > i+1 && nums[j] == nums[j-1] {
    				continue
    			}
    			head, tail := j+1, n-1
    			for head < tail {
    				sum := nums[i] + nums[j] + nums[head] + nums[tail]
    				switch true {
    				case sum < target:
    					head++
    				case sum > target:
    					tail--
    				default:
    					res = append(res, []int{nums[i], nums[j], nums[head], nums[tail]})
    					for head < tail && nums[head] == nums[head+1] {
    						head++
    					}
    					for head < tail && nums[tail] == nums[tail-1] {
    						tail--
    					}
    					head++
    					tail--
    				}
    			}
    		}
    		return res
    	}
    }
    

      

  • 相关阅读:
    js没有重载
    零基础学习hadoop到上手工作线路指导(初级篇)
    hadoop1.x和2.x的一些主要区别
    LIBCURL教程
    钩子函数大全(2)
    Visual Studio快捷键
    Linux上搭建Hadoop2.6.3集群以及WIN7通过Eclipse开发MapReduce的demo
    Hadoop2.7.1安装与配置
    超详细单机版搭建hadoop环境图文解析
    Windows下运行Hadoop
  • 原文地址:https://www.cnblogs.com/csp813/p/15601522.html
Copyright © 2020-2023  润新知