leetcode刷题笔记十六 接近三数之和 Scala版本

leetcode刷题笔记十六 接近三数之和 Scala版本

源地址:16. 最接近的三数之和

问题描述:

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

简要思路分析:

本题思路基于上一题,通过先对数组进行排序后使用双指针方法。

代码补充:

object Solution {
    def threeSumClosest(nums: Array[Int], target: Int): Int = {
        val sortArr = nums.sorted
        var closeResult = Int.MaxValue
        var tempResult = 0
        var ansResult = 0
        
        for(iCur <- 0 until sortArr.length-2){
            var left = iCur + 1
            var right = sortArr.length - 1
            while(left < right){
               //println("iCur: "+iCur)
               //println("left: "+left)
               //println("right: "+right)
               //println("Sum: "+(sortArr(iCur) + sortArr(left)+sortArr(right)))
               var arrSum =  sortArr(iCur) + sortArr(left)+sortArr(right) 
               arrSum match{
                    case sum if sum < target =>  {tempResult = target - arrSum;left+=1;if (tempResult < closeResult) {ansResult=arrSum;closeResult=tempResult}}
                    case sum if sum > target =>  {tempResult = arrSum - target;right-=1;if (tempResult < closeResult) {ansResult=arrSum;closeResult=tempResult}}
                    case sum if sum == target => return sum  
               }
               
           }  
        }
        return ansResult
    }
}

猜你喜欢

转载自www.cnblogs.com/ganshuoos/p/12715982.html
今日推荐