如何找到数组中最长的序列?我有一个5的数组(用户输入)和10的数组(随机彩票号码1-100),我想找出用户猜测的最长序列。例如:彩票号码是:10 12 13 15 17 18 19 20 32 65和用户猜测1 2 15 17 18。这将是一个3数字序列,我想找出用户猜测的是2,3,4或所有数字。我怎么做?这是我的密码,请帮我,我已经被困在这几个小时了。
// to check if user guessed a sequence
int counter=0;
String prize3;
int counter1,counter2,counter3,counter4;
for (int i = 0; i < lottery.length - 5; i++) { // 1-5
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 1; i < lottery.length - 4; i++) { // 2-6
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 2; i < lottery.length - 3; i++) { // 3 -7 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 3; i < lottery.length - 2; i++) { // 4 - 8 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 4; i < lottery.length - 1; i++) { // 5 -9 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 5; i < lottery.length; i++) { // 6 -10 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 0; i < numbers.length && i < 2; i++) { // first 2 numbers of input
counter1 = numbers[i];
}
for (int i = 0; i < numbers.length && i < 3; i++) { // first 3 numbers of input
counter2 = numbers[i];
}
for (int i = 0; i < numbers.length && i < 4; i++) { // first 4 numbers of input
counter3 = numbers[i];
}
for (int i = 0; i < numbers.length && i < 5; i++) { // all numbers of input
counter4 = numbers[i];
}
2条答案
按热度按时间sdnqo3pr1#
根据您提供的输入,我假设彩票号码数组总是排序的。在这种假设下,应用二进制搜索是非常合适的。
这是我非常简单的暴力方法。
变量cnt将输出序列的长度。
xwmevbvl2#