找出一個數組中既不是最大的數也不是最小的數,我的java代碼如下(錯誤的):
class NotMM{
public void NotMM(int arr[]){
int mid = arr[0];
for(int i=0;i<arr.length-2;i++){
if(arr[i+1]>arr[i]&&arr[i+1]<arr[i+2]){
mid = arr[i+1];
}else if(arr[i+1]<arr[i]&&arr[i+1]>arr[i+2]){
mid = arr[i+1];
}else if(arr[i]<arr[i+1]&&arr[i]>arr[i+2]){
mid = arr[i];
}else if(arr[i]>arr[i+1]&&arr[i]<arr[i+2]){
mid = arr[i];
}else{
mid = arr[i+2];
}
System.out.println(mid);
}
}
}
public class Ex1_4 {
public static void main(String[] args) {
NotMM m = new NotMM();
int arr[] = new int[]{2,4,6,1,7,5,3,8};
m.NotMM(arr);
}
}
請大俠改正,用簡單的算法,謝謝!
排序之後掐頭去尾,然後隨機選一個