我在一次采访中被问到这个问题。第一部分相当简单,我必须编写代码来获取数组中连续整数的最大数量。以下是我写的代码:
int count = 0, max = 0;
for(int i = 1; i < array.length; i++) {
if((array[i - 1] + 1) == array[i])) //curr is consecutive to prev
count++;
else
count = 0; //reset the counter as sequence is broken
//Keep track of maximum
if(count > max)
max = count;
}
System.out.println(max); //print the length of largest consecutive integers
第二部分是关于它的后续问题:
您将如何修改此逻辑以适用于存储在多台机器中的数组?