我想写一个简单的算法来识别整数的ArrayList
中第一个丢失的实数。我很难编写逻辑。观察我的代码片段:在序列中查找缺失数字的逻辑是什么?
// 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
。帮帮我?
对于你的榜样,你会希望它也匹配7?序列总是会增加1吗? – PlasmaPower
可能是因为'我'只是一个int 0,1,2,3。它甚至不会达到'4',因此它不可能超过序列中的任何值。 –
@PlasmaPower否和N/A。它只需要找到第一个缺失值,并且序列可以是任何已排序的整数列表。 – Elliott