剑指offer_数组---旋转数组的最小数字
来源:互联网 发布:女权运动 知乎 编辑:程序博客网 时间:2024/06/13 22:13
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
解题思路
1,使用Arrays.sort
2,暴力遍历法
3,二分查找
代码实现
package 数组;import java.util.Arrays;public class MinNumberInRotateArray { public static void main(String[] args) { int[] array = { 1,1,1,0,1 }; System.out.println(new MinNumberInRotateArray() .minNumberInRotateArraySuperFind(array)); } // =========================================================非技巧解法利用Arrays的sort函数,直接排序O(nlogn) public int minNumberInRotateArray(int[] array) { if(array==null||array.length<1){ throw new RuntimeException("数组不合法"); } Arrays.sort(array); return array[0]; } // ==========================================================技巧解法,暴力遍历法O(n) public int minNumberInRotateArraySuper(int[] array) { if(array==null||array.length<1){ throw new RuntimeException("数组不合法"); } int i = 0; for (; i < array.length; i++) { if (array[i] > array[i + 1]) { break; } } return array[i + 1]; } // ==========================================================技巧解法,二分查找法O(logn) public int minNumberInRotateArraySuperFind(int[] array) { if(array==null||array.length<1){ throw new RuntimeException("数组不合法"); } int low = 0; int high = array.length-1; int middle =0; while(low<high){ middle = (high+low)/2; if(array[middle]>array[high]){ //middle在左边递增区间 low = middle+1; //最小值在middle右边 }else if(array[middle]==array[high]){ //1,1,1,0,1这样没有办法只能顺序遍历 Arrays.sort(array); return array[0]; } else{ high = middle; //middle在右边递增区间,最小值在middle或者middle左边 } } return array[low]; }}
阅读全文
0 0
- 剑指offer_数组---旋转数组的最小数字
- 剑指Offer_面试题08_旋转数组的最小数字
- 【剑指offer】旋转数组的最小数字
- 剑指offer--旋转数组的最小数字
- 剑指offer--旋转数组的最小数字
- 剑指offer:旋转数组的最小数字
- 《剑指offer》旋转数组的最小数字
- 剑指 offer:旋转数组的最小数字
- 剑指offer6 旋转数组的最小数字
- 剑指offer-旋转数组的最小数字
- 剑指offer 旋转数组的最小数字
- 【剑指offer】旋转数组的最小数字
- 剑指offer 旋转数组的最小数字
- 剑指offer-旋转数组的最小数字
- 剑指Offer:旋转数组的最小数字
- 剑指Offer 旋转数组的最小数字
- 剑指offer|旋转数组的最小数字
- 剑指offer:旋转数组的最小数字
- leetcode344. Reverse String
- ecmall 支付成功订单状态没有改变解决办法
- QML TEXT元素
- Handler,Thread 和HandlerThread三者之间关系
- 各种语言HMAC SHA256实现
- 剑指offer_数组---旋转数组的最小数字
- Nginx服务器中的location配置详解
- 关于客户登录案例的思考
- git基础操作
- socket与http的区别
- python zip函数
- ndoejs+mongodb 开发5:批量修改
- 归并排序的简单实现
- 简单的斐波那契数列