【演算法】--- 先減後增陣列找最大,先增後減陣列找最小,先增後增找最小
阿新 • • 發佈:2018-12-09
- 先減後增陣列找最大
- public int turningPoint(int[] A) {
- int m = A.length;
- int begin = 0;
- int end = m - 1;
- int tp = begin + (end - begin)/2;
- // the condition "tp > 0 && tp < m -1" makes sure that tp is not at the beginning or the end
- while (tp > 0 && tp < m -1) {
- if (A[tp] > A[tp + 1] && A[tp] > A[tp -1]) {
- return tp;
- } else if (A[tp] < A[tp+1]) {
- begin = tp + 1;
- tp = begin + (end - begin)/2;
- } else {
- end = tp - 1;
- tp = begin + (end - begin)/2;
- }
- }
- return -1;