关于golang:Leetcode专题数组18四数之和

5次阅读

共计 1037 个字符,预计需要花费 3 分钟才能阅读完成。

力扣链接:https://leetcode-cn.com/probl…
解题思路:

  1. 之前尝试过很多刷题的办法,一方面感觉是本人的技术积攒和对语言的理解使用的确还差火候,另一方面是刷题的思路不对,依照题目程序来刷或者单纯依照难度来刷都有其缺点,首先依照题目程序来刷,实际上每个题目的知识点都不雷同,东一榔头,西一棒槌,很难系统性的学习某个知识点,依照难度来耍,一开始就上 mid 或者 hard 的题目,很快就会因为畏难而造成刷题效率大打折扣。这次采纳了新的办法,首先分门别类,如数组 / 链表 / 树 / 动静布局等,而后每个类别先从简略刷题,每个类别每个难度刷 20 道题。通过一段时间的验证当前,有事倍功半的成果
  2. 回到这道题自身,三数之和 / 最靠近的三数之和 / 四数之和,实质上都是采纳一种办法,那就是排序 + 双指针,最初两位数肯定是双指针,那么后面残余的数字就是须要循环遍历的
  3. 这道题为了优化一个不须要的便当,对边界做了一些优化,当然这些都是小优化,不扭转实质的算法
func fourSum(nums []int, target int) [][]int {n := len(nums)
    sort.Ints(nums)
    ans := make([][]int, 0)
    for i := 0; i < n-3 && nums[i]+nums[i+1]+nums[i+2]+nums[i+3] <= target; i++ {if i > 0 && nums[i] == nums[i-1] || nums[i]+nums[n-1]+nums[n-2]+nums[n-3] < target {continue}
        for j := i + 1; j < n-2 && nums[i]+nums[j]+nums[j+1]+nums[j+2] <= target; j++ {if j > i+1 && nums[j] == nums[j-1] || nums[i]+nums[j]+nums[n-1]+nums[n-2] < target {continue}
            k, l := j+1, n-1
            for k < l {sum := nums[i] + nums[j] + nums[k] + nums[l]
                if sum == target {ans = append(ans, []int{nums[i], nums[j], nums[k], nums[l]})
                    for k++; k < l && nums[k] == nums[k-1]; k++ { }
                    for l--; k < l && nums[l] == nums[l+1]; l-- {}} else if sum > target {l--} else {k++}
            }
        }
    }
    return ans
}
正文完
 0