• 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
        }
    }
    
  • 相关阅读:
    数据倾斜原理及解决方案
    删除emp_no重复的记录,只保留最小的id对应的记录
    理解HBase面向列存储
    给数据库用户授权(对象多为系统表,如dba可以查看的表)
    SpringBoot里的一些注解
    01背包
    【转】简说GNU, GCC and MinGW (Lu Hongling)
    费马小定理
    欧拉定理
    【转】C中的静态存储区和动态存储区
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/12715982.html
Copyright © 2020-2023  润新知