3-SUM问题的O(n²)算法

来源:互联网 发布:网络创世纪安卓 编辑:程序博客网 时间:2024/05/19 19:41

Coursera的测试题,要找一个算法,使得3-sum问题的算法的计算时间为O(n^2),其中n是数组的长度。题目中假设,排序的计算时间是优于O(n^2)的。

这里借助于二次循环,先求出 sum-a-b 再利用HashMap的containsValue()方法,判断这个差是否在集合中。当然其中有一些细节需要注意,一个是需要对数组进行排序,其次需要准备一个数组,b,b[i]表示a[i]在这个数组中的重复次数。(中间有些粗糙的处理ps:我司新人)

import java.util.Arrays;import java.util.HashMap;public class Three_sum {public static void cal(int[] a, int sum){int cha = 0;//构建一个哈希表,将a中的元素存入哈希表中,先对A进行排序升序Arrays.sort(a);HashMap<Integer, Integer> map = new HashMap<>();int[] b = new int[a.length];for(int i = 0; i < a.length; i++){ //n//初始时,每一个元素都只有一个b[i] = 1;map.put(i, a[i]);}//首先计算一下重复数的个数,用b[i]表示a[i]所拥有的重复数字的个数for(int i = 0; i < a.length; i++) {   //这个算法是 n^2操作数for( int j = i + 1; j < a.length; j++){if(a[i] == a[j]){b[i] ++;b[j] ++;}}}for(int i = 0; i < a.length; i++) {for(int j = i + 1; j < a.length; j++) {cha = sum - a[i] - a[j];//由于存在大小关系,所以这个时候我们只会考虑大于a[i]和a[j]的数if(map.containsValue(cha)){if(cha >= a[i] && cha >= a[j]) {if(cha == a[i] && cha == a[j] && b[i] >= 3){//此时存在三个相同的数,其和为sumSystem.out.println(a[i] + " " + a[j] + " " + cha );}else if(cha == a[i] && cha != a[j] && b[i] >= 2){//此时存在两个相同的数,一个不同的数System.out.println(a[i] + " " + a[j] + " " + cha );}else if(cha != a[i] && cha == a[j] && b[j] >= 2){System.out.println(a[i] + " " + a[j] + " " + cha );}else if(cha != a[i] && cha != a[j]){//此时一定存在System.out.println(a[i] + " " + a[j] + " " + cha );}}}}}}public static void main(String[] args) {int a[] = {-1, 0, 1, 2, 3, -2, -3};int sum = 0;cal(a, sum);}}