在反轉數組中查找最小值,最大值

數組[4,5,6,7,0,1,2]

 

package com.search;

public class BinaryFindMin {
	public static void main(String[] args) {
		int[] num = new int[]{4,5,6,7,-1,0,2};
		System.out.println(findMin(num));
	}
	public static Integer findMin(int [] num){
       if(num == null || num.length == 0) {
       	 return null;
       }
       int start = 0;
       int end = num.length - 1;
       //假設最小目標值爲target
       int target = num[end];
       while(start + 1 < end) {
       	 // 取中間值mid
       	 int mid = start + (end - 1) / 2;
       	 // 如果中間值索引比target小。說明最小值在左邊的區間
       	 if(num[mid] <= target) {
       	 	end = mid;
       	 } else {
       	 	start = mid;
       	 }
       }
       return num[start] > num[end] ? num[end] : num[start];
	}
}

那麼最大值其實也是一樣的道理,舉一反三

  public static Integer findMax(int[] num) {
    if (num == null || num.length == 0) {
      return null;
    }
    int start = 0;
    int end = num.length - 1;
    // 假設最大目標值爲target
    int target = num[end];
    while (start + 1 < end) {
      // 取中間值mid
      int mid = start + (end - 1) / 2;
      // 如果中間值索引比target小。說明最小值在左邊的區間
      if (num[mid] >= target) {
        start = mid;
      } else {
        end = mid;
      }
    }
    return num[start] > num[end] ? num[start] : num[end];
  }

如果數組中存在多個重複值,如[0,0,0,0,0,0,0,1,2,2,2,2],這個時候只能用傳統的迭代方法

 public static Integer findDuplicateMin(int[] num) {
    if (num == null || num.length == 0) {
      return null;
    }
   	int  min = num[num.length-1];
   	for(int start = 0;start < num.length;start++) {
   		if(min > num[start]) {
   			min = start;
   		}
   	}
   	return num[min];
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章