Find the smallest value in the rotated sorted array

Source: Internet
Author: User

Suppose a rotated sorted array whose starting position is unknown (e.g. 0 1 2 4 5 6 7 May become 4 56 7 0 1 2).

You need to find the smallest of these elements.

You can assume that there are no duplicate elements in the array.

Idea: Dichotomy method

1, judge whether the smallest number is in the first position, if it returns NUMS[0];

2, otherwise, select the middle position mid and the number of R position to compare, if NUMS[MID] < Nums[r], indicating the smallest number in Mid, R = Mid; Conversely, make L = mid+1;

3, repeat, until L >= R.

public class Solution {
/*
* @param nums:a rotated sorted array
* @return: The minimum number in the array
*/
public int findmin (int[] nums) {
Write your code here
int l = 0;
int r = nums.length-1;
if (Nums[l] < Nums[r]) {
return nums[l];
}
while (L < R) {
int mid = (l+r)/2;
if (Nums[mid] > Nums[r]) {
L = mid + 1;
}else{
R = Mid;
}
}
return nums[l];
}
}

Find the smallest value in the rotated sorted array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.