ECNU || 回文串

java超时代码

import java.util.Scanner;
public class Main{
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n+1];
        for(int i = 1; i <= n; i++){
            a[i] = sc.nextInt();
        }
        int i = 1,j = n,flag = 0;
        while(i < j){
            if(a[i] == a[j]){
                i++;
                j--;
            }
            if(i >= j){
                break;
            }
            if(a[i] < a[j]){
                i++;
                a[i] = a[i-1] + a[i];
                flag++;
            }
            else if(a[i] > a[j]){
                j--;
                a[j] = a[j] + a[j+1];
                flag++;
            }
        }
        System.out.println(flag);
    }
}

C++代码

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <set>
#define maxn 1000005
using namespace std;
 
typedef long long ll;
ll a[maxn];
 
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
    }
    int i=1,j=n,flag=0;
    while (i<j)
    {
        if(a[i]==a[j])
        {
            i++;
            j--;
        }
        if (i>=j) break;//最重要的一句!!!!!!!
        if(a[i]<a[j])
        {
            i++;
            a[i]=a[i-1]+a[i];
            flag++;
        }
        else if(a[i]>a[j]){
            j--;
            a[j]=a[j]+a[j+1];
            flag++;
        }
        //if(i==j) break;//!!!!!!!
    }
     printf("%d\n",flag);
    return 0;
}

你可能感兴趣的:(刷题)