程序11-先升序后降序返回最大值

来源:互联网 发布:cad网络培训班 编辑:程序博客网 时间:2024/05/21 01:58

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

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));    }}

感觉用电脑写代码要比在纸上写代码爽多了,而且考虑的更周全;但是,面试时给个电脑,调试不出来怎么办?

0 0
原创粉丝点击