【LeetCode-面試演算法經典-Java實現】【153-Find Minimum in Rotated Sorted Array(找旋轉數組中的最小數字)】

來源:互聯網
上載者:User

標籤:數組   尋找   面試   演算法   java   

【153-Find Minimum in Rotated Sorted Array(找旋轉數組中的最小數字)】 【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】 原題

  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.

題目大意

  假設一個排序的數組以事先未知的某個中樞進行了旋轉。
  即,0 1 2 4 5 6 7可能成為4 5 6 7 0 1 2)。
  找到最小的元素。
  你可以假設不存在重複的數組中。

解題思路

  二分搜尋法,數組分為兩個有序的部分,前一個部分和後一個部分並且前一個排序部分元素都比後一個元素大隻要找到後一個元素比前一個大就是要找的元素

代碼實現

演算法實作類別

public class Solution {    public int findMin(int[] nums) {        // 參數檢驗        if (nums == null || nums.length < 0) {            throw new IllegalArgumentException();        }        return binarySearch(nums, 0, nums.length - 1);    }    public int binarySearch(int[] nums, int start, int end) {        int mid = 0;        while (start < end) {            mid = start + ((end - start) >> 1);            // 後一個數比前個數小就找到了            if (nums[mid]> nums[mid + 1]) {                return nums[mid + 1];            }            // 說明中間值在第一個有序的數組中            else if (nums[mid] > nums[start]) {                start = mid;            }            // 說明中間值在第二個有序的數組中            else {                end = mid;            }        }        // 說明整個數組是有序的        return nums[0];    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明 歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47828181】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【153-Find Minimum in Rotated Sorted Array(找旋轉數組中的最小數字)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.