import java.util.*;
//Given nums = [2, 7, 11, 15], target = 9,
//Because nums[0] + nums[1] = 2 + 7 = 9,
//return [0, 1].
//思路:先建立一个int[2]数组result存放返回值,然后遍历,
//其中一个为cur=nums[i],另一个toFind=target-nums[i],//如果发现之前需要这个差值,那就找index。
//如果没有,就put到map里 //返回result,循环结束
public class Solution { public int[] twoSum(int[] nums, int target) {
//创建一下数组,要存两个index的数组。
int[] result = new int[2]; //这里用hashtable也行,看心情。
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//扫一遍数组,一边扫一边存
for(int i = 0; i < nums.length; i++)
{ int cur = nums[i]; //这里搞出来个差值,其实差值是在没找到之后添加到map里面的。
int toFind = target - cur;
//如果发现之前需要这个差值,那就找index。
if(map.containsKey(cur)){ result[0] = map.get(cur); result[1] = i; return result; }
//如果没有,就put到map里面
else{ map.put(toFind, i);
} }
return result;
}}
如果遇到threeSum呢?fourSum?
【题目】
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
提示:
- a<=b<=c
- 避免结果集中有重复,因为数组时排好序的,所以当一个数被放到结果集中的时候,其后面和它相等的直接被跳过。
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)【思路】
K Sum问题是一个系列,博客 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 和https://blog.csdn.net/ljiabin/article/details/40620579总结得比较完整,有兴趣可以去看。
暴力解决法:三层for循环,但是时间复杂度是O(n^3),而且还要处理重复的问题,显然不是题目想要的解法。
排序算法:时间复杂度为O(nlgn),小于O(n^2),那么我们不妨先对数组排个序。
对于3Sum ,我们可以先固定一个数,然后找另外两个数之和为第一个数的相反数就可以了。
【Java代码】O(n^2)
- public class Solution {
- List<List<Integer>> ret = new ArrayList<List<Integer>>();
- public List<List<Integer>> threeSum(int[] num) {
- if (num == null || num.length < 3) return ret; //如果数组元素个数<3
- Arrays.sort(num); //调用Arrays的sort方法对num从小到大排序;
- int len = num.length; //用for循环遍历,若两个元素相等,则跳出,调用find(),寻找两个数与num[i]的和为0;
- for (int i = 0; i < len-2; i++) {
- if (i > 0 && num[i] == num[i-1]) continue;
- find(num, i+1, len-1, num[i]); //寻找两个数与num[i]的和为0
- }
- return ret;
- }
- //find方法,num[l] + num[r] + target == 0,则这三个值add到列表对象中
- public void find(int[] num, int begin, int end, int target) {
- int l = begin, r = end;
- while (l < r) {
- if (num[l] + num[r] + target == 0) {
- List<Integer> ans = new ArrayList<Integer>();
- ans.add(target);
- ans.add(num[l]);
- ans.add(num[r]);
- ret.add(ans); //放入结果集中
- while (l < r && num[l] == num[l+1]) l++;
- while (l < r && num[r] == num[r-1]) r--;
- l++;
- r--;
- } else if (num[l] + num[r] + target < 0) {
- l++;
- } else {
- r--;
- }
- }
- }
- }
注意,对于 num[i],寻找另外两个数时,只要从 i+1 开始找就可以了。