leetcode刷题笔记十八 四数之和 Scala版本
作者:互联网
leetcode刷题笔记十八 四数之和 Scala版本
源地址:18. 四数之和
问题描述:
Given an array
nums
of n integers and an integertarget
, are there elements a, b, c, and d innums
such that a + b + c + d =target
? Find all unique quadruplets in the array which gives the sum oftarget
.
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]
]
代码补充:
//import scala.collection.mutable.ListBuffer
object Solution {
var ansList = List[List[Int]]()
def fourSum(nums: Array[Int], target: Int): List[List[Int]]= {
//如果nums的长度小于4个数,返回[]
if (nums.length < 4) return List()
//符合条件的情况下,将ansList重新更新
ansList = List[List[Int]]()
var sortArr = nums.sorted
var result = List[Int]()
//设置Nlength=4,执行函数
findNsum(sortArr, target, 4, result)
return ansList
}
//将4数问题或者说N数之和问题分解为2数之和问题
//当sortArr.length < Nlength 或者 Nlength < 2的情况时直接返回
//当Nlength == 2时,将left设为有序数组的首部,将right设为有序数组的尾部
//当left < right时,计算sortArr(left)+sort(right)的值与target进行比较,类似与双指针方法
// 当Nlength > 2时,排除target<Nlength * sortArr(0) 和
// target > Nlength * sortArr(sortArr.length-1)的情况
// 针对i分割
def findNsum(sortArr:Array[Int],target:Int,Nlength:Int,result:List[Int]): Unit={
if (sortArr.length < Nlength || Nlength < 2) return
if (Nlength == 2){
var left = 0
var right = sortArr.length - 1
while (left < right){
val Tsum = sortArr(left)+sortArr(right)
Tsum match{
case sum if (sum < target) => left += 1
case sum if (sum > target) => right -= 1
case sum if (sum == target) =>{
//println ((result++List(sortArr(left),sortArr(right))))
ansList = ansList :+ result++List(sortArr(left),sortArr(right))
println(ansList)
do (left+=1) while(left == 0 || (left < right && sortArr(left) == sortArr(left-1)))
do (right-=1)while(right>left && sortArr(right) == sortArr(right+1))
}
}
}
}
else{
//println(Nlength)
for (i <- 0 to sortArr.length-Nlength if(target >= sortArr(0)*Nlength || target <= sortArr(sortArr.length-1)*4)){
if(i == 0 || (i > 0 && sortArr(i-1)!=sortArr(i))){
findNsum(sortArr.slice(i+1,sortArr.length),target-sortArr(i),Nlength-1,result.concat(List(sortArr(i))))
}
}
}
}
}
标签:四数,target,Scala,sortArr,List,Nlength,right,leetcode,left 来源: https://www.cnblogs.com/ganshuoos/p/12728359.html