一、Problem
輸入
輸入一個數n。
輸出
輸出三角形的個數。
5
4 5 6 7 8
10
二、Solution
方法一:暴力
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
int N;
int[] A;
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
N = sc.nextInt();
A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = sc.nextInt();
}
int res = 0;
for (int i = 0; i < N-2; i++)
for (int j = i+1; j < N-1; j++)
for (int k = j+1; k < N; k++) {
int a = A[i], b = A[j], c = A[k];
if (a+b <= c || a + c <= b || b + c <= a) continue;
if (a-b >= c || a - c >= b || b - c >= a) continue;
res++;
}
System.out.println(res);
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
複雜度分析
- 時間複雜度:,大概 的計算量,容易超時…
- 空間複雜度:,
方法二:滑動窗口
- 固定一個最大值,其下標了 i,然後左右指針 l、r 在 i 的左側維護一個窗口。
- 如果有 ,則一定也有 。
- 所以,只需累加區間的大小即可。
- 但前提是數組需要有序。
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int N = sc.nextInt();
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = sc.nextInt();
}
Arrays.sort(A);
long res = 0;
for (int i = N-1; i >= 2; i--) {
int l = 0, r = i-1;
while (l < r) {
if (A[l] + A[r] > A[i]) {
res += r - l;
r--;
} else {
l++;
}
}
}
System.out.println(res);
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,