Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time

来源:互联网 发布:大话设计模式 php pdf 编辑:程序博客网 时间:2024/06/01 19:01

题目要求:

Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case. You may assume that you can sort the n integers in time proportional to n2 or better.

分析:

《算法4》这本书提供的TwoSumFast解法为NlogN,ThreeSumFast解法为N2logN,根据课后练习,要实现3Sum复杂度为N2,建议先把2Sum复杂度实现为N。同时教材提示用排好序的数组可以实现复杂度N。我想了很久,没有发现排好序的数组对复杂度降至N有太大帮助,于是在网上搜索了下大家的做法。网上的大部分都是建议用set或map来做,我决定采用map试试,果然用map很方便。代码如下:

import java.util.Arrays;import java.util.HashMap;public class TwoSumLinear {public static int count(int[] a){int cnt = 0;int n = a.length;HashMap map = new HashMap();for(int i =0; i

3Sum的作业提示可以先将数组排序,基于这个思路,结合写过的2Sum线性实现方法,写出了复杂度为N2的3Sum,个人认为实现的方式已经很精简了。

import java.util.Arrays;import java.util.HashMap;public class ThreeSumQuadratic {public static int count(int[] a, int target) {Arrays.sort(a);// 数组从小到大排序,后面要使用有序数组的性质简化运算System.out.println(Arrays.toString(a));System.out.println("target="+target);int cnt = 0;int n = a.length;HashMap map = new HashMap();for (int i = 0; i < n; i++) {map.put(a[i], i); //以数组value为key,index为map值}for (int i = 0; i < n - 1; i++) {//i不会超过n-2for (int j = i + 1; j < n; j++) {//j从i+1开始统计,不会超过n-1int smallValue = a[i] + a[j]; //因为排好序了,所以最开始的a[i]+a[j]if (smallValue > target) //当a[i]+a[j]>target时没必要计算了,因为后续的查找就会重复break;int bigValue = target-smallValue; //计算出对应的数值较大的valueInteger bigIndex = map.get(bigValue); //查找数值较大的value所在的位置if (bigIndex != null && bigIndex > i && bigIndex > j) {System.out.println("[" + i + "]=" + a[i] + ",[" + j + "]" + a[j] + ",[" + bigIndex + "]" + (bigValue));cnt++;}}}return cnt;}public static void main(String[] args) {int[] a = { 30, -40, -20, -10, 40, 0, 10, 5 };System.out.println(count(a,0));}}