Java版PAT甲级1044

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f?tpId=37&tqId=21271&rp=1&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking&tab=answerKey
两组数据超时,用C++重写通过

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] str = reader.readLine().split(" ");
        int N = Integer.parseInt(str[0]);
        int M = Integer.parseInt(str[1]);
        str = reader.readLine().split(" ");
        int[] arr = new int[N + 1];
        for (int i = 1; i <= N; i++) {
            arr[i] = arr[i - 1] + Integer.parseInt(str[i - 1]);
        }
        StringBuilder sb = new StringBuilder();
        int min = Integer.MAX_VALUE;
        for (int i = 1, j = 0; i <= N; i++) {
            while (arr[i] - arr[j + 1] >= M) j++;
            if (arr[i] - arr[j] >= M) min = Math.min(arr[i] - arr[j], min);
        }
        for (int i = 1, j = 0; i <= N; ) {
            if (arr[i] - arr[j] == min) {
                sb.append(j + 1).append("-").append(i).append("\n");
                i++;
                j++;
            } else if (arr[i] - arr[j] > min) {
                j++;
            } else {
                i++;
            }
        }
        System.out.println(sb.substring(0, sb.length() - 1));
    }
}

#include<iostream>
#include<cstdio>

using namespace std;
int n, m;
int INF = 1e9;
int arr[100010];
int main() {
    ios::sync_with_stdio(false);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		cin >> arr[i];
		arr[i] += arr[i - 1];
	}
    int temp = INF;
    for (int i = 1, j = 0; i <= n; i++) {
        while (arr[i] - arr[j + 1] >= m) j++;
        if (arr[i] - arr[j] >= m) temp = min(arr[i] - arr[j], temp);
    }
    for (int i = 1, j = 0; i <= n; ) {
        if (arr[i] - arr[j] == temp) {
           cout << j + 1 << '-' << i << endl;
            i++;
            j++;
        }
        else if (arr[i] - arr[j] > temp) {
            j++;
        }
        else {
            i++;
        }
    }
    return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页