public static int count(int[] a) { int N = a.length; Arrays.sort(a); int cnt = 0; for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j++) { int k = Arrays.binarySearch(a, -(a[i] + a[j])); if (k > j) cnt++; } } return cnt; }
【在 j**y 的大作中提到】 : 找了半天也没找到下面算法 : There is a simple algorithm to solve 3SUM in O(n2) time. : 有code吗 多谢
G*0
14 楼
再多弄点review
L*a
15 楼
可怜,长的时候卡住了吧。。。
g*e
16 楼
this is O(n^2*lgn). there is o(n^2) algorithm. use head and tail pointers in your second loop to do the search.
【在 j**y 的大作中提到】 : : public static int count(int[] a) { : int N = a.length; : Arrays.sort(a); : int cnt = 0; : for (int i = 0; i < N; i++) { : for (int j = i+1; j < N; j++) { : int k = Arrays.binarySearch(a, -(a[i] + a[j])); : if (k > j) cnt++; : }
【在 j**y 的大作中提到】 : Find a pair of numbers that sums up to zero (or any other number), then : find three (and then four) numbers that sum up to zero : 有什么好的方法? 多谢