Leetcode001两数之和(解题思路-java解法-scala解法)

解题思路

 

Java解法

package leetcode;

import java.util.HashMap;

public class L01两数之和java {
    public static void main(String[] args) {

    }

    public int[] twoSum(int[] nums, int target) {
        // 定义一个hashmap
        HashMap<Integer, Integer> map = new HashMap<>();
        // 遍历数组
        for (int i = 0; i < nums.length; i++) {
            // map中包含target - nums[i]) ,直接返回 map.get(target - nums[i]), i
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            } else {
                map.put(nums[i], i);
            }
        }
        // 找不到就返回空数组
        return new int[0];
    }
}

Scala解法

package leetcode



/*
hash表解法
 */
object L01两数之和 {

  def main(args: Array[String]): Unit = {

    val result = twoSum(Array(2, 7, 11, 15), 9)
    println(result.mkString(","))

  }

  def twoSum(nums: Array[Int], target: Int): Array[Int] = {
    // TODO 新建一个可变的Map[Int,Int]空集合
    import scala.collection.mutable
    var hashtable = mutable.Map[Int,Int]()

    // 使用索引方式遍历 nums 数组
    for (i <- nums.indices) {
      // 如果 map中包含 target-nums(i) 说明找打了两数之和 ,返回一个数组,里面是两数的索引
      if (hashtable.contains(target - nums(i))) {

        return Array[Int](hashtable(target - nums(i)), i)

      } else {
        // 如果map不包含,将 num(i),i 添加到map中
        hashtable(nums(i)) = i
      }
    }
    // 没有找到返回空数组
    Array[Int]()
  }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值