Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

寻找旋转排序数组中的最小值 #129

Open
louzhedong opened this issue Feb 14, 2019 · 0 comments
Open

寻找旋转排序数组中的最小值 #129

louzhedong opened this issue Feb 14, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第153题

假设按照升序排序的数组在预先未知的某个点上进行了旋转。

( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

请找出其中最小的元素。

你可以假设数组中不存在重复元素。

示例 1:

输入: [3,4,5,1,2]
输出: 1

示例 2:

输入: [4,5,6,7,0,1,2]
输出: 0

思路

使用二分法来解答,如果mid的元素大于最右边的元素,说明最小值在mid的右边,否则就在左边。当mid的元素小于mid -1 的元素时,mid即为最小值。

解答

var findMin = function (nums) {
  var length = nums.length;
  var left = 0, right = length - 1, mid = 0;
  while (left <= right) {
    mid = left + Math.floor((right - left) / 2);
    if (nums[mid] < nums[mid - 1]) break;
    if (nums[mid] > nums[right]) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  return nums[mid];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant