先升序后降序返回最大值

一个数列,先升序后降序,返回最大值的下标。

package org.fan.learn;

/**
 * Created by fan on 2016/10/10.
 */
public class BinarySearchMeituan {

    public static int search(int[] arr) {
        //特殊处理
        if (arr == null || arr.length == 0) {
            return -1;
        }

        int result = 0;
        int start = 0;
        int end = arr.length - 1;
        int mid = 0;
        //end-1防止只有两个数据  没有等于号防止只有1个数据
        while (start < end - 1) {
            mid = start + ((end - start) >>> 1);
            if (arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1]) {
                return mid;
            }
            if (arr[mid] > arr[mid-1] && arr[mid] < arr[mid+1]) {
                start = mid+1;
            }
            if (arr[mid] < arr[mid-1] && arr[mid] > arr[mid+1]) {
                end = mid - 1;
            }
        }

        if (start == end) {
            result = start;
        }
        if (start < end) {
            result = arr[start] > arr[end] ? start : end;
        }

        return result;
    }

    public static void main(String[] args) {
        //6,7,8,9,4,5,6
        //9
        //6,7
        //6,5
        int[] arr = {4,6,5};
        System.out.println(search(arr));
    }
}

原文链接:程序11-先升序后降序返回最大值

发布了149 篇原创文章 · 获赞 931 · 访问量 181万+

猜你喜欢

转载自blog.csdn.net/liuweiyuxiang/article/details/100905327