1. Two Sum
2017-04-21 本文已影响0人
CNSumi
Description:
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.
有一个整型数组和一个目标值,返回可以两个相加的和为目标值的下标。
每个输入有且仅有一个正确的输出,每个元素只能使用一次。
Samples:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solutions
<ol>
<li>O(n^2)的解决方案
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if ((nums[i] + nums[j]) == target) {
return new int[] {i, j};
}
}
}
return new int[] {1, 1};
}
}
因为在题目中假设每个用例有且仅有一个解,所以下面的return new int[] {1, 1};
不会被执行到。这种解法的时间复杂度为大O平方阶,不需要额外的空间。</li>
<li>O(n)的解决方案
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[0] = map.get(target - nums[i]);
result[1] = i;
return result;
}
map.put(nums[i], i);
}
return result;
}
}
这种方法将每次遍历的数值存储在map中,以值为key,以位置为值,这样在下次需要这个值时从map中取出返回。</li>
</ol>
TestCase
<ol>
<li>[[10,2,3,1,7], 10]</li>
<li>[]