• LeetCode——Find Minimum in Rotated Sorted Array


    Description:

    Suppose a sorted array is rotated at some pivot unknown to you beforehand.

    (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

    Find the minimum element.

    You may assume no duplicate exists in the array.

    随机找一个枢纽,旋转有序数组,找出最小元素。

    O(n)解法,线性查找。1ms

    public class Solution {
        public int findMin(int[] nums) {
            
            int min = nums[0];
            
            for(int i=1; i<nums.length; i++) {
                if(min > nums[i])
                    min = nums[i];
            }
            
            return min;
        }
    }

    O(logn)解法,二分。0ms

    public class Solution {
        public int findMin(int[] nums) {
            
            int n = nums.length - 1;
            
            int left = 0, right = nums.length - 1;
            
            while(left <= right) {
                int mid = left + (right - left) / 2;
                if(nums[mid] > nums[n]) {
                    left = mid + 1;
                }
                else {
                    right = mid - 1;
                }
            }
            
            return nums[left];
        }
    }
  • 相关阅读:
    单(single)
    cdq分治
    寿司
    qtth
    二分,倍增的一些思考(lost my music:可持久化栈)
    手写堆、哈希表
    保留字,关键字
    测试19,20,21
    要买的书
    测试18:T2:可爱精灵宝贝
  • 原文地址:https://www.cnblogs.com/wxisme/p/4859779.html
Copyright © 2020-2023  润新知