- 描述
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, whereindex1 must be less than index2.
Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
- 分析
用双循环求解,时间复杂度为O(n^2)
利用HashMap按key读取value复杂度为O(1)这个特性,将数组元素的值作为key,下标作为value,这样可以很快获得相应元素的下标,这样时间复杂度O(n),空间复杂度O(n)
package leet.TwoSum;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static int[] getTwoSum(int[] arr, int target) {
int[] result = new int[2];
// 利用HashMap按key读取复杂度为O(1)这个特性,
// 将数组的元素值作为key,下标作为value,这样可以很快获得相应元素的下标
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; ++i) {
if(!map.containsKey(arr[i]))
map.put(arr[i], i);
int n = target - arr[i];
if(map.containsKey(n) && map.get(n) != null && map.get(n)<i) {
result[1] = i + 1;
result[0] = map.get(n) + 1;
return result;
}
}
return result;
}
}
网友评论