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
原题链接:https://leetcode.com/problems/two-sum/
大概意思是:给出一个整型数组以及一个target数字,求数组中两个数之和为target的数的下标,下标顺序大到小。。。
结题都用java
方法一 双向指针,时间复杂度O(nlogn)
public class Solution {
class Pair implements Comparable<Pair> {
int value, index;
public Pair(int v, int id) {
value = v;
index = id;
}
@Override
public int compareTo(Pair b) {
return this.value - b.value;
}
}
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
Pair[] pairs = new Pair[nums.length];
System.out.println(nums.length);
// get pairs and sort
for (int i = 0; i < nums.length; ++i) {
pairs[i] = new Pair(nums[i], i + 1);
}
Arrays.sort(pairs);
// two points
int left = 0, right = nums.length - 1, sum = 0;
while (left < right) {
sum = pairs[left].value + pairs[right].value;
if (sum == target) {
res[0] = pairs[left].index;
res[1] = pairs[right].index;
if (res[0] > res[1]) {
// swap them
int temp;
temp = res[1];
res[1] = res[0];
res[0] = temp;
}
break;
} else if (sum > target) {
--right;
} else {
++left;
}
}
return res;
}
}
方法二:
后来发现了有另一种机智的答题方法:利用map键值对的便利,key存储值,value存下标,时间复杂度也是O(n),先看代码,后面在解释复杂度的问题
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
res[0] = -1;
res[1] = -1;
final HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (h.containsKey(target - nums[i])) {
int index = h.get(target-nums[i])+1;
res[0] = Math.min(i+1, index);
res[1] = Math.max(i+1, index);
}
h.put(nums[i], i);
}
return res;
}
}
这位答题者的链接:https://leetcode.com/discuss/62838/o-n-time-o-n-space-solution-in-java
其实就是利用了hashmap的containsKey,一般来说hashmap的containskey效率是O(1),最坏情况是O(n)。大家可以了解一下hashmap的存储原理,其实是利用了二维的数组,大大的缩小了查找的效率。