美文网首页
TwoSum Scala写法

TwoSum Scala写法

作者: FredricZhu | 来源:发表于2020-04-11 10:54 被阅读0次
package twosum

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.Map

object Solution {
  /**
   * i的平方时间复杂度
   */
  def twoSum(nums: Array[Int], target: Int): Array[Int] = {
    val len = nums.length
    val res = Array[Int](-1, -1)
    var m = 0
    for {
      i <- 0 to len - 1
      j <- i+1 to len - 1
      if (nums(i) + nums(j) == target && m ==0)
    } {
      m += 1
      res(0) = i
      res(1) = j
    }
    res
  }
  
  /**
   * 查字典,key为数组value值,value为索引值
   * 时间复杂度为n
   */
  def twoSum1(nums: Array[Int], target: Int): Array[Int] = {
    val res = Array[Int](-1, -1)
    var map = Map[Int, ListBuffer[Int]]()
    val len = nums.length
    for {
      i <- 0 to len -1
    } {
      if(!map.contains(nums(i)))  map(nums(i)) = ListBuffer[Int](i) else map(nums(i)).append(i)
    }
    
    for {
      j <- 0 to len - 1 
    } {
      val key = target - nums(j)
      if(map.contains(key)) {
        for{ele <- map(key)} {
          if(ele != j) {
            res(0) = ele
            res(1) = j
          }
        }
      }
    }
    res
  }
  
  
  def main(args: Array[String]): Unit = {
    val res = twoSum1(Array[Int](1, 2, 3, 4, 5, 6, 7, 8, 9), 5)
    println(res(0))
    println(res(1))
  }
}

相关文章

网友评论

      本文标题:TwoSum Scala写法

      本文链接:https://www.haomeiwen.com/subject/xqaemhtx.html