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
        }
    }
    
  • 相关阅读:
    appium 命令安装记录
    用命令方式启动、停止appium服务和app
    adb连接网易mumu模拟器
    获取APP包名,launcherActivity
    jekins配置
    Appium工作原理
    关于An association from the table XX refers to an unmapped class错误
    什么是MYSQL回表查询
    MySQL的in和or的效率问题
    MYSQL语句优化
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/12715982.html
Copyright © 2011-2022 走看看