1. Two Sum

44次阅读

共计 504 个字符,预计需要花费 2 分钟才能阅读完成。

Given an array of integers, return indices of the two numbers suchthat they add up to a specific target.You may assume that each input would have exactly one solution, andyou 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].1. 暴力 O(n^2)2. 排序后双指针 O(nlogn)3.hash o(n)

public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap();
for(int i=0;i<nums.length;++i){
int need=target-nums[i];
if(map.containsKey(need)) return new int[]{i,map.get(i)};
map.put(nums[i],i);
}
throw null;
}

正文完
 0

1. Two Sum

44次阅读

共计 992 个字符,预计需要花费 3 分钟才能阅读完成。

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};
}
}

正文完
 0