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].
难度:easy
题目:
给定一整数数组,返回使得数组中两元素的和为特定整数的下标。
假定每个输入都会有且仅有一个结果,不可以重复使用同一个元素。
思路:
- 利用hash map
- 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)
if (mii.contains(adder)) {
return Array(mii.get(adder).get, 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};
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。