首页 > 解决方案 > How to find if in an array of scores each score is equal to or lower than the one preceding it?

问题描述

Under some set of scores the code "misbehave" and ending with false result. This occurs for example on this set of scores:

5, 4, 3, 2, 5

As long as the numbers decreasing everything is fine, but at the last step, where it's increasing again, the code fails to return the right answer.

Any help and explanation would be really appreciated.

Task Given an array of scores, print 'true' if each score is equal to or lower than the one preceding it. Input Format The first line contains a single integer, n, denoting the size of the array. Each of the subsequent n lines contains a single integer denoting the value of the array at the next position. Constraint The length of the array will be 2 or more. Output Simply the word 'true' or 'false'.

Input 5 4 3 2 1 1 Expected Output true Output true Input 5 4 3 2 1 2 Expected Output false Output true

Already tried multiple solutions by my own but I'm an absolutely beginner, all my attempts failed.

    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();

    int[] array3 = new int[a];
    int m; int j = 1; int ctn=-1;

    //System.out.println("ctn= -1");
    for(int i=0; i<array3.length; i++){ 
        m = sc.nextInt();
        while(j<array3.length && array3[j] < m){
            j++;
        }          
            if(j == array3.length){    
                array3[i] = m;
                ctn++;
                j = 0;
                //System.out.println("ctn+1 m>j " + ctn);
            }else{
                array3[i] = m;
                j = 0;
                //System.out.println("ctn m<=j " + ctn);
            }
    }

    if(ctn != 0){
        System.out.println("false");
    }else{
        System.out.println("true");
    }
}

}

标签: java

解决方案


编辑:我不完全确定您是否希望每个分数等于或低于它之前的所有分数(或)它之前的直接分数

如果它只是它之前的直接分数,那么一个带有查找的简单循环来检查以前的值就可以了,否则请参阅下面的内容。


执行此操作的简单方法是跟踪您迄今为止遇到的最低“分数”并将其用于检查条件。

Scanner scan = new Scanner(System.in);
int count= scan.nextInt();
int lowest = Integer.MAX_VALUE;
boolean flag = false;
for(int i=0;i<count;i++) {
    int current = scan.nextInt();
    if(lowest<current) {
        flag = true;
        break;
    } else if(current<lowest) {
        lowest = current;
    }
}
if(flag) {
    System.out.println("false");
} else {
    System.out.println("true");
}

推荐阅读