zoukankan      html  css  js  c++  java
  • 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
        }
    }
    
  • 相关阅读:
    理解HashSet及使用
    Java 集合类详解
    Java-泛型编程-使用通配符? extends 和 ? super
    回调函数及其用法
    log4j.properties 详解与配置步骤
    约瑟夫环
    泛型的约束与局限性
    把代码字体加大的办法
    System.arraycopy方法
    泛型数组列表与反射
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/12715982.html
Copyright © 2011-2022 走看看