解题思路
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]()
}
}