Two Sum
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, where index1 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
Title大意:
给定一个数组和一个目标整数,求在数组中的两个和为目标函数的下标,第一个下标要小于第二个下标(确保有且只有一个结果)
Solution:
O(n2) runtime, O(1) space – Brute force:
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).
O(n) runtime, O(n) space – Hash table:
We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
1.暴力破解,两个for循环,令tmp = target减去数组中的一个数,找到数组里的另一个数,时间复杂度O(n^2)
2.利用HashMap,Hash存储和查找时间O(1)
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++){
map.put(nums[i], i);
}
int[] res = new int[2];
for(int i=0;i<=nums.length;i++){
int tmp = target - nums[i];
if(map.get(tmp)!=null && map.get(tmp)!=i){
res[0] = i + 1;
res[1] = map.get(tmp) + 1;
break;
}
}
return res;
}
}