问题陈述是找到每个相邻数字的总和,最后打印出第二个最高和和两个相邻的数字。
条件 - 只有一个循环。
public class AdjencentSumOfWithSecondHighest {
public static void main(String[] args) {
int[] arr = {2, 5, 3, 8, 9, 1, 7};
int[] newArr = new int[arr.length - 1];
int highest = arr[0], previoushighest = highest;
int index = 0, prevIndex = 0;
for (int i = 0; i < arr.length - 1; i++) {
newArr[i] = arr[i] + arr[i + 1];
if(highest < newArr[i]){
previoushighest = highest;
highest = newArr[i];
prevIndex = index;
index = i;
}
}
System.out.println("Second Highest NO : "+previoushighest);
System.out.println("no one is "+arr[prevIndex]+ " and no two is "+arr[index]);
}
}
工作非常好。但如果在数组中有重复的数字,则错误的结果如{2,5,3,3,8,9,1,7}
答案 0 :(得分:0)
更新:新
这可能会对你有帮助。
int[] arr = { 2, 5, 3, 3, 3, 3, 1, 7 } ;
int[] newArr = new int[arr.length - 1];
int highest = arr[0]+arr[1], previoushighest = Integer.MIN_VALUE;
int index = 0, prevIndex = 0;
for (int i = 0; i < arr.length - 1; i++) {
newArr[i] = arr[i] + arr[i + 1];
if (highest < newArr[i]) {
int temp=highest;
highest = newArr[i];
previoushighest=temp;
index = i;
}
else if( previoushighest < newArr[i] && highest>newArr[i]){
previoushighest=newArr[i];
prevIndex=i;
}
}
System.out.println("Second Highest NO : " + previoushighest);
System.out.println("Highest NO : " + highest);
System.out.println("no one is " + arr[prevIndex] + " and no two is "
+ arr[index]);
我不明白。为什么要打印这条线
System.out.println("no one is " + arr[prevIndex] + " and no two is "
+ arr[index]);
答案 1 :(得分:0)
这对我来说很好..至少到目前为止所讨论的案例(还不确定是否完整)。
int[] arr = { 2, 4, 3, 3, 3, 3, 1, 7,8};
int[] newArr = new int[arr.length - 1];
int highest = arr[0], previoushighest = Integer.MIN_VALUE;
int index = 0; // to capture position of second highest pair's second element
int hindex = 0; // to capture position of highest pair's second element
if(arr.length < 3) {
System.out.println("No second highest exists");
return;
}
for (int i = 0; i < arr.length - 1; i++) {
newArr[i] = arr[i] + arr[i + 1];
if(previoushighest < newArr[i]){
if(highest < newArr[i]){
previoushighest = highest;
highest = newArr[i];
index = hindex;
hindex = i+1;
} else if(highest != newArr[i]) {
previoushighest = newArr[i];
index = i+1;
} else {
continue;
}
}
}
System.out.println("Second Highest NO : "+previoushighest);
System.out.println("no one is "+arr[index-1]+ " and no two is "+arr[index]);