几乎增加序列java

gan*_*892 1 java arrays for-loop

我正在尝试编写代码来确定是否可以通过仅从该数组中删除一个元素来获得严格递增的整数数组。

我的代码适用于 17 种情况中的 16 种,但无法想出一种方法来巧妙地重写我的代码,以便解决一个数字大于它之前的数字以及小于它之后的数字的情况我已经写了这个 for 循环。这是我的代码。这不起作用的情况是数组:[1, 2, 3, 4, 3, 6],因为它不认为数组中的最后 3 个作为我的 for 循环当前构造方式的违规者.

boolean almostIncreasingSequence(int[] sequence) {

int offenderPosition = 0;
int[] arrCopy = Arrays.copyOf(sequence, sequence.length);
boolean ordered = true;


//trying to neatly rewrite this for loop 
for(int i= 0; i < sequence.length; i++){
    if(i<sequence.length-1){
        for(int j = i+1; j < sequence.length; j++) {
            if(!(sequence[i] < sequence[j])){
                ordered = false;
                offenderPosition = i;
            }
        }
    }
    if(i == sequence.length-1){
        if(!(sequence[i] > sequence[i-1])){
            ordered = false;
            offenderPosition = i; 
        }
    }

}


if(ordered == false) {
    //remove offender 
    int currentSize = arrCopy.length;
    for(int i = offenderPosition+1;i< currentSize; i++) {
        arrCopy[i-1] = arrCopy[i];
    }
    currentSize--;

    //reassign array
    arrCopy = Arrays.copyOf(arrCopy, currentSize);

    boolean lastChance = true;

    for(int i = 0; i < currentSize-1; i++){
        for(int j = i+1; j < currentSize; j++) {
            if(!(arrCopy[i] < arrCopy[j])){
                lastChance = false;
            }
        }
    }
    return lastChance;
}
else{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

}

Faz*_*iqi 9

我认为这可能有效:

boolean almostIncreasingSequence(int[] a) {
    int count1 = 0 , count2 = 0;
    for(int i = 0 ; i < a.length-1 ; i++){
        if(a[i] >= a[i+1]) count1++;
    }

    for(int i = 0 ; i < a.length-2 ; i++){
        if(a[i] >= a[i+2]) count2++;
    }
     return (count1 <=1) && (count2 <= 1);
}
Run Code Online (Sandbox Code Playgroud)

第一个循环只检查彼此靠近的数字。如果第一个索引大于第二个索引,我们将向 count1 加 1。当将 1 添加到 count1 时,这意味着第一个索引大于第二个索引,该方法应该返回 false;第二个 for 循环也将检查 ex。如果第一个索引大于第三个索引。例如 1, 2 ,1,2 它将在 count2 上加 1 在每个循环执行后,该方法将返回 if 语句返回的布尔值。