如何解决如何在Java中找到最长的双值数组?
我需要帮助来找到最长的双值数组的长度。为了满足作为双值数组值显示的是两个唯一数字。例如,这是一些例子
int A []= {4,2,4,2} in this case there are two different numbers length would be 5
int A []= {1,3,2} in this case there are three different number,if you look into first two
different numbers bi-valued array length would be 2 but if you look in to index[1] - length-1,there
are two different number and its three (2,2) so the length becomes 3.
this is what my code looks like
public static int biValuedArrLength(int [] a){
int count = 0;
if(a.length == 2) return 2;
for(int i = 0; i<a.length; i++){
//need help how can I accomplish this task
//
}
}
提前谢谢!
解决方法
使用它。我正在使用内部循环来获取最大长度。
public static int biValuedArrLength(int [] a){
int count = 0;
if(a.length == 2) return 2;
int maxLength = 0;
for(int i = 0; i<a.length; i++){
int firstNo = a[i];
int secondNo = firstNo;
for(int j=i+1;j<a.length;j++) {
int currLength = j-i+1;
if(a[j]!=firstNo && a[j]!=secondNo){
if(secondNo==firstNo) {
secondNo = a[j];
} else {
break;
}
}
if(currLength > maxLength) {
maxLength = currLength;
}
}
}
return maxLength;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。