Alomerry Wu @ alomerry.com

18. 四数之和

Sep 21, 2022 · 1min · 283 ·

Description

Difficulty: 中等

Related Topics: Array, Two Pointers, Sorting

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

  • 0 <= a, b, c, d < n
  • a, b, c, and d are distinct.
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

Constraints:

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109

Solution

Language: Go

定边双指针法:固定两边,指针 i、j 从两边向内计算,如果当前四数之和大于(小于)target,则移动 j(i)想中间靠拢。为了防止超时,需要进行一定的剪枝:当 i、j 确定出一个 target 的解,则需要移动 i、j,移动时需要保证新的 nums[i]、nums[j] 的值是变化了的,否则无论是哪一个值变动都只能让总和更小或者更大,同时也能避免计算了相同解。

IOI

 
 comment..
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.0.1
Theme by antfu
2018 - Present © Alomerry Wu