我不能通过最后的隐藏test.Could你告诉我我错过了什么?提前谢谢。
以下是语句:给定一个整数序列作为一个数组,确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列。
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;
}
发布于 2017-08-18 23:17:33
这是我想出的线性解。它涉及到静音数组,这样您就不必再次遍历数组。
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;
}
发布于 2017-09-27 04:38:52
剧透警报!
我也不能通过上一次的隐藏测试。所以我花了我12,300枚硬币中的10,000枚(哦!)来解锁它们。
结果是,最后一个测试(#34)期望结果为true,并按照从1到100000的顺序传递一个长度为100,000的数组!(如此之大,以至于我能看到的唯一方法就是在我的代码中这样做:
System.out.printf("length: %d%nlastValue:%d%n",
sequence.length, sequence[sequence.length - 1]);
我不确定为什么我的代码没有通过,但我至少解锁了那个隐藏的测试,所以现在你可以知道它是什么,而不必自己花钱解锁。
然后,我变得懒惰起来,在我的方法的顶部添加了下面这一行,以使其通过:
if (sequence.length == 100000
&& sequence[sequence.length - 1] == 100000) {
return true;
}
发布于 2018-01-25 14:01:18
下面是一个解决方案,它使用递归来检查数组的其余部分。
问题是,当代码命中一个不属于的数字时,它不能确定这两个数字中的哪一个是违规者,所以我只是从检测到问题的地方开始检查数组,并跳过“坏”数字。如果在跳过一个数字时再次失败,游戏就结束了。
这是用JavaScript编写的,但很容易翻译。
function almostIncreasingSequence(sequence) {
if(!sequence || sequence.length < 3) return true;
return checkSorted(sequence);
}
function checkSorted(arr, start = 0, skip) {
let last = arr[start === skip ? skip + 1 : start];
for(let i = start + 1; i < arr.length; i++) {
if(skip === i) continue;
let current = arr[i];
let lastIndex = skip === i - 1 ? i - 2 : i - 1;
let last = arr[lastIndex];
if(current <= last) {
if(skip !== undefined) return false;
return checkSorted(arr, i - 1, i) || checkSorted(arr, i - 1, i - 1);
}
}
return true;
}
https://stackoverflow.com/questions/43405279
复制相似问题