我正在尝试编写一个简单的算法来识别ArrayList
整数中第一个缺失的实数。我在编写逻辑时遇到了困难。观察我的代码snippit:
// suppose sequence is a valid sorted ArrayList
int match = 0;
int first = sequence.get(0); // sets the first value in seq. to var
int size = sequence.size(); // sets the seq size to var
for (int i = 0; i < size; i++)
{
if (i != sequence.get(i) && i > first)
match = i; // it is not in the sequence
}
System.out.println(match + " is not in the sequence.");
如果序列为4, 5, 8, 9
,我希望match
为6
。相反,我得到了0
。帮助
答案 0 :(得分:3)
这是因为您的if
条件要求sequence.get(i)
等于i
。相反,它应该是first + i
,并且需要删除条件的第二部分:
if ((first + i) != sequence.get(i)) {
match = (first + i);
break;
}
答案 1 :(得分:1)
试试这个:
int max = -1;
for(int i=1; i<sequence.size(); i++) {
if(sequence.get(i) > sequence.get(i - 1)) {
match = i + 1;
break;
}
}
System.out.println(match + " is not in the sequence.");
答案 2 :(得分:0)
支票类似于sequence.get(i+1) == sequence.get(i) + 1
。如果失败,您将返回sequence.get(i) + 1
。
答案 3 :(得分:0)
import java.util.Arrays;
import java.util.List;
/**
<P>{@code java FindMissingNumInSequence}</P>
**/
public class FindMissingNumInSequence {
public static final void main(String[] ignored) {
List<Integer> ascUnqIntList = Arrays.asList(4, 5, 8, 9);
int num = ascUnqIntList.get(0); //Initialize to the first one
for(int i : ascUnqIntList) {
if(num != i) {
System.out.println("First missing number in sequence: " + num);
break;
}
System.out.println(i);
num++;
}
}
}
输出:
[C:\java_code\]java FindMissingNumInSequence
4
5
First missing number in sequence: 6
答案 4 :(得分:0)
这应该可以帮助您获得所需的内容,假设数组列表已经排序。
for (int i = 0; i < size - 1; i++)
{
if (sequence.get(i+1) - sequence.get(i) > 1 ) {
match = sequence.get(i) + 1; // it is not in the sequence
break;
}
}
答案 5 :(得分:0)
Array (ans1,ans2,ans3);
答案 6 :(得分:0)
public class MissingNumber {
public static void main(String[] args) {
MissingNumber num=new MissingNumber();
int[] numb={2,4,6,10,12,14,};
num.solution(numb);
}
public int solution(int[] A) {
int j=0;
int k=0;
int missingNum=0;
int[] arrayInt=A;
int diff=0;
for(int i=0;i<arrayInt.length-2;i++)
{
j=arrayInt[i+1]- arrayInt[i];
k=arrayInt[i+2]-arrayInt[i+1];
if(j==k){
diff= k;
}
if(j!=k)
{
if(j!=diff)
{
missingNum=arrayInt[i]+diff;
}
else if(k!=diff){
missingNum=arrayInt[i+1]+diff;
}
}
}
System.out.println("Missing number"+missingNum);
return missingNum;
}
}