gpt4 book ai didi

java - Q : Solve almostIncreasingSequence in Java (Codefights)

转载 作者:行者123 更新时间:2023-11-29 07:30:34 25 4
gpt4 key购买 nike

我无法通过最后的隐藏测试。你能告诉我我错过了什么吗?提前致谢。

语句如下:给定一个整数序列作为数组,确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列。

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;
}

最佳答案

这是我想出的线性解决方案。它涉及使数组静音,因此您不必再次遍历数组。

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 - Q : Solve almostIncreasingSequence in Java (Codefights),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43405279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com