AcWing 1210. 连号区间数(枚举)

Problem

这个题的数据量是104,暴力枚举+排序+依次判断是要超时的
因为题面说了1-N,N个数的排列,那么没有重复的数,直接列首列尾的差值可以反应是否已经排好序,则可以省略判断和排序的时间。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

class Main {
     
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 10010, n;
    static int a[] = new int[N];

    public static void main(String[] args) throws IOException {
     
        String ss[] = br.readLine().split(" ");
        n = Integer.parseInt(ss[0]);
        ss = br.readLine().split(" ");
        for (int i = 0; i < n; i++) {
     
            a[i] = Integer.parseInt(ss[i]);
        }
        int res = 0;

        for (int i = 0; i < n; i++) {
     
            int max = -N, min = N;
            for (int j = i; j < n; j++) {
     
                max = Math.max(max, a[j]);
                min = Math.min(min, a[j]);
                if (max - min == j - i) res++;
            }
        }
        pw.print(res);
        pw.flush();
        pw.close();
        br.close();
    }
}

你可能感兴趣的:(基础算法)