# 1. Two Sum

XAMPP下载 778浏览

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

sort 后从两头向中间夹挤
Runtime: 352 ms, faster than 96.77% of Scala online submissions for Two Sum.

object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
import scala.collection.mutable.Map
val mii: Map[Int, Int] = Map()
for (i ← 0 until nums.size) {
val adder = target – nums(i)
}
mii += (nums(i) → i)
}
Array(0, 0)
}
}
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> mii = new HashMap<>();
/*
* 从前向后遍历，既然是一定会有匹配的数，那只能是前面找不到对应的，后面可以找到找出的index应该是前的。所以后面遍历的i作为右边index
*/
for (int i = 0; i < nums.length; i++) {
if (mii.containsKey(target – nums[i])) {
return new int[] {mii.get(target – nums[i]), i};
}
mii.put(nums[i], i);
}

return new int[] {0, 0};
}
}