They are actually the same problem.
2-sum:
my code:
比较简单的一道题。扫过每个数,寻找与这个数和为target,并且已经扫过的数。如果存在就return,不存在就放入map继续扫。
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {
int part = target - nums[i];
if (map.containsKey(part))
return new int[]{map.get(part),i};
map.put(nums[i], i);
}
throw new IllegalArgumentException("No Solution");
}
}
分析:
running time : around O(nlgn), "lgn" is the time for put and get. put and get usually O(1)-O(n), depends on the situation. JDK 8, average around lgn.
space: O(n);