Binary search LeetCode33 rotation sorted array

Search in Rotated Sorted Array

description

Suppose a sorted array, and then the rotation Pivot according to one, such as [1,2,3,4,5,6,7,8] -> [6,7,8,1,2,3,4 5].
Your task is to rotate find the array after a number in the subscript, subscript such as 6 to 1, and if this number does not exist, -1 is returned.
Requirements: time complexity of O (log (n))

solution

  • Obviously we should expect to see logn divide and rule (Divide and Conquer). How to use the D & C There are three ways
      1. This problem easiest way is through divide and rule first find the pivot mentioned above, the "spin" Go back, then go to have this number.
      1. According to "spin" feature, in addition to the array will find somewhere step occurred, the other is increasing. Mid no matter where, there is always one side (left-> mid, mid-> right ) is monotonically increasing. So that we can always incrementally determine the relationship between the position of mid and target edges.
      1. For 2 further summarizes the improved method, nums[0]<=target, target<=nums[i], nums[i]<nums[0]the three conditions contains all the circumstances, and then XOR wrote a concise way: https://leetcode-cn.com/problems/search-in-rotated-sorted-array/ solution / ji-jian-solution- by-lukelee /

Boundary conditions

  • Obviously, the above is not difficult to think of ideas, we thought at least the second step can be done, but the boundary conditions still need to think about.
  • Boundary binary search algorithm, generally divided into two cases, one is left closed right-open interval, similar to the [left, right), one is left close right close range, similar to the [left, right]. It should be noted It is cyclic in vitro initialization conditions, the loop iteration step the body, must comply with the rules consistent interval.
  • The best way to Programming Pearls given:
int search4(int array[], int n, int v)
{
int left, right, middle;

left = -1, right = n;

while (left + 1 != right)
{
    middle = left + (right - left) / 2;

    if (array[middle] < v)
    {
        left = middle;
    }
    else
    {
        right = middle;
    }
}

if (right >= n || array[right] != v)
{
    right = -1;
}

return right;
}

Reference: https://blog.csdn.net/weixin_43705457/article/details/87874779

Guess you like

Origin www.cnblogs.com/SsoZhNO-1/p/12498466.html