最近看算法4中遇到的以前没注意到的问题:
求数组中三个数和为0的个数ThreeSum
package com.learn.mstake;
/**
* @Author: shixiaofei
* @Description:
* @Date: 2019/6/10 16:20
* @Version: 1.0
*/
public class ThreeSum {
public static void main(String[] args) {
int arr[] = new int[]{1, -1, 0, 2, -2, 0, 1, 2, 3};
int count = count(arr);
System.out.println(count);
}
public static int count(int[] a) {
int length = a.length;
int cnt = 0;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
for (int k = j + 1; k < length; k++) {
if (a[i] + a[j] + a[k] == 0) cnt++;
}
}
}
return cnt;
}
}
语句执行频率分别是N、N(N-1)/2、N(N-1)(N-2)/6
①1+2+3+...+n-1
②1+2+3+...n-2
...
前n项和为N*(N-1)*(N-2)/6
证明:
1+2+3+……+N=N(N+1)/2=(N²+N)/2
1²+2²+……N²=N(N+1)(2N+1)/6
所以数列各项加起来就是:
S(N)=(1²+1)/2+(2²+2)/2+(3²+3)/2+……+(N²+N)/2
=[(1²+2²+3²+……+N²)+(1+2+3+……+N)]/2
=[N(N+1)(2N+1)/6+N(N+1)/2]/2
=N(N+1)[(2N+1)/6+1/2]/2
=N(N+1)(N+2)/6
其中n=n-2
附:
1²+2²+...+n²
(n+1)^3 - n^3 = 3*n^2 + 3*n + 1,可以得到下列等式:
2^3 - 1^3 = 3*1^2 + 3*1 + 1
3^3 - 2^3 = 3*2^2 + 3*2 + 1
4^3 - 3^3 = 3*3^2 + 3*3 + 1
.........
(n+1)^3 - n^3 = 3.n^2 + 3*n + 1
以上式子相加得到
(n+1)^3 - 1 = 3*Sn + 3*n(n+1)/2 + n
其中Sn = 1^2 + 2^2 + 3^2 + ...... + n^2
化简整理得到:
Sn = n*(n + 1)*(2n + 1)/6
static int count;
static int count1;
public static void main(String[] args) {
int n=10;
anInt(n);
System.out.println(count1);
System.out.println(count);
int sum1=n*(n-1)/2;
int sum3=(n-2)*(n-1)*n/6;
System.out.println(sum1);
System.out.println(sum3);
}
public static void anInt(int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
count1++;
for (int k = j + 1; k < n; k++) {
count++;
}
}
}
}
输出结果: