问:解决Java中的几乎增加的序列(Codefights) [英] Q: Solve almostIncreasingSequence in Java (Codefights)
本文介绍了问:解决Java中的几乎增加的序列(Codefights)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法通过最终的隐藏测试.能告诉我我想念的是什么吗?
I can't pass the final hidden test.Could you tell me what I miss?Thanks in advance.
以下语句:给定整数序列作为数组,请确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列.
Here are the statements: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
boolean almostIncreasingSequence(int[] sequence)
{
boolean increase = true;
List<Integer> list = new ArrayList<>();
for (int a :sequence )
{
list.add(a);
}
System.out.println(list);
if(list.size()==1)
{
return false;
}
for (int i = 0;i < list.size()-1 ;i++ )
{
if (list.get(1)<=list.get(0))
{
list.remove(0);
break;
}
if(list.get(i+1)<=list.get(i))
{
if (list.get(i+1)>list.get(i-1))
{
list.remove(i);
}
else
{
list.remove(i+1);
}
break;
}
}
for (int i =0;i<list.size()-1 ;i++ )
{
if (list.get(i+1)<list.get(i) || list.get(i+1)==list.get(i) )
{
increase = false;
}
}
return increase;
}
推荐答案
这是我想出的线性解决方案.它涉及使数组静音,因此您不必再次遍历数组.
This is the linear solution I came up with. It involves muting the array so you don't have to loop through the array again.
boolean almostIncreasingSequence(int[] sequence) {
int removed = 0;
for (int i = 0; i < sequence.length - 2 && removed <= 2; i ++) {
int a = sequence[i];
int b = sequence[i+1];
int c = sequence[i+2];
if (a >= b) {
removed++;
sequence[i] = b -1;
}
if (b >= c){
removed++;
if (a == c) {
sequence[i+2] = b +1;
} else {
sequence[i+1] = a;
}
}
}
return removed <= 1;
}
这篇关于问:解决Java中的几乎增加的序列(Codefights)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文