Data structure binary search OJ (on)

content

1. Binary search

 2. Search for the insertion position

3. Search first and last position in sorted array

4. Search the minimum value of the rotated array

5. Search Rotation Array II

6. Search Rotation Array (Interview Question)

7. Find the minimum value in a rotated array

8. Search for minimum value in rotated array II

9. Find the local minimum number in an array


1. Binary search

Corresponding letecode link:

704. Binary Search - LeetCode (leetcode-cn.com)

Topic description:

Problem solving ideas:

 

 First, calculate the subscript of the middle position according to the subscript of the starting position of the array and the subscript of the end position, and then compare the value of the middle position with the value to be searched.

In this image:

Since the element to be found, 20, is greater than the middle element, 12, locate the middle element of the right half of the array again:

 Just found the element 20.

If the length of the array is N, then the time complexity is O(log N) and the space complexity is O(1).

Corresponding code:

class Solution {
public:
    int search(vector<int>& nums, int target) {
          int left=0;
          int right=nums.size()-1;
          int ans=-1;
          while(left<=right){
            int mid=(left+right)>>1;//求中点
            if(nums[mid]==target){//找到了
                ans=mid;
                break;
            }
            else if(nums[mid]<target){
                left=mid+1;
            }
            else{
                right=mid-1;
            }

          }
        return ans;

    }
};

 2. Search for the insertion position

35. Search Insertion Location - LeetCode (leetcode-cn.com)

 Topic description:

Problem solving ideas:

The idea of ​​this question is very similar to the previous question. You only need to find the leftmost element that is greater than or equal to the target. The algorithm flow is as follows:

1. Find the midpoint and compare the target

2. If the value of the end position is greater than or equal to the target, then cut and adjust the right

3. If the value of the end position is less than the target, cut the left one.

4. If the target is more than all the elements in the array, it means that it is inserted at the end of the array.

Corresponding code:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
            int index=-1;//记录答案下标
            int left=0;
            int right=nums.size()-1;
              while(left<=right){

                int mid=(left+right)>>1;
                if(nums[mid]>=target){//大于等于往左边走找到最左边大于等于target的位置
                    index=mid;
                    right=mid-1;
                }
                else{
                    left=mid+1;
                }
            }
            return index==-1?nums.size():index;//如果上面没有更新过答案说明插入位置在数组的末尾
    }
};

3. Search first and last position in sorted array

Corresponding letecode link:

34. Find the first and last position of an element in a sorted array - LeetCode (leetcode-cn.com)

 Topic description:

 Problem solving ideas:

1. Use binary search to find the rightmost position smaller than target

2. +1 the returned position to see if it has crossed the boundary or the value is not equal to target

3. Find the rightmost position smaller than target+1, that is, target.

Corresponding code:

class Solution {
public: 
       int FindIndex(vector<int>&nums,int target){
           int left=0;
           int right=nums.size()-1;
           int ans=-1;//记录答案找比target小的最右的位置
           while(left<=right){
               int mid=(left+right)>>1;
               if(nums[mid]<target){//只要比target要小就记录答案
                      left=mid+1;
                      ans=mid;
               }
               else{
                     right=mid-1;
               }
           }
           return ans;
       }
    vector<int> searchRange(vector<int>& nums, int target) {
                int L=FindIndex(nums,target)+1;//在比target小的最右边的位置在加个1
                
                if(L==nums.size()||nums[L]!=target){//如果已经越界了或者这个位置的值不是target
                    return {-1,-1};
                }
                return {L,FindIndex(nums,target+1)};//找到比target+1小的最右边的数即target

    }
};

4. Search the minimum value of the rotated array

Corresponding letecode link:

153. Find the minimum value in a rotated sorted array - LeetCode (leetcode-cn.com)

Topic description:

Problem solving ideas:

 Problem solving ideas:

1. Define a variable to record the answer

2. Take the midpoint and compare the value on the left. If the value on the left is less than or equal to the value on the right, it means that the left is ordered. When judging whether the target is in this interval, if it is in right=mid-1, otherwise left=mid+1.

3. If the left side is out of order, it means that the right side is in order, and the same judgment is made if it is in this interval, if it is left=mid+1, otherwise right=mid-1.

Take the following example:

 

According to the above figure, we can intuitively see a rule, how to judge whether it is disturbed by rotation? The precondition for normal ascending order is first element <= last element, and the condition for disordered order is: first element > last element

Then continue to dig the law of disordered array, that is order in disorder, how to understand it?

 

 Corresponding code:

class Solution {
public:
    int search(vector<int>& nums, int target) {
         if(nums.empty())//如果为空
          return -1;
        int left=0;
        int right=nums.size()-1;
        int ans=INT_MAX;
        while(left<=right){
            int mid=(left+right)/2;
            if(nums[mid]==target)
              ans=mid;
            if(nums[mid]>=nums[left]){//如果左边有序
                if(target>=nums[left]&&target<=nums[mid]){//如果在这个区间里面
                    right=mid-1;
                }

                else{
                    left=mid+1;
                }

            }
            else{//右边有序
                
                if(target>=nums[mid]&&target<=nums[right]){
                         left=mid+1;
                }

                else{
                    right=mid-1;
                }
                 
                }
        }
        return  ans==INT_MAX?-1:ans;
    }
};

5. Search Rotation Array II

Corresponding letecode link:

81. Search Rotation Sorted Array II - LeetCode (leetcode-cn.com)

Topic description

Problem solving ideas:

The difference between this question and the previous question is that there may be repeated elements. When the values ​​on the left and right are equal, we cannot judge the order of the two intervals [left,,mid] and [mid,right]. So we need to delete the part on the right, the value of which is equal to the value on the left, and follow the idea of ​​the above question.

Corresponding code:

class Solution {
public:
    bool search(vector<int>& arr, int target) {
        int l = 0, r = arr.size() - 1;
        int ans = INT_MAX;
          while(l < r && arr[l] == arr[r]){
                r--;
            }
        while(l <= r){
          
            int mid = (l+r)/2;
            if(arr[mid] == target){//相等找到了
                ans = mid;
                break;
            }
            if(arr[l] <= arr[mid]){//左边有序
                if(arr[l] <= target && target <= arr[mid]){
                    r = mid - 1;
                }else {
                    l = mid + 1;
                }
            }else {//右边有序
                if(arr[mid] <=  target && target <= arr[r]){
                    l = mid + 1;
                }else {
                    r = mid - 1;
                }
            }
        }
        return ans == INT_MAX ? false : true;
    }
};

6. Search Rotation Array (Interview Question)

Corresponding letecode link:

Interview Question 10.03. Searching Rotation Arrays - LeetCode (leetcode-cn.com)

Topic description:

 Problem-solving ideas: It is basically the same as the previous question, but the answer needs to be updated.

Corresponding code:

class Solution {
public:
    int search(vector<int>& arr, int target) {
              int l = 0, r = arr.size() - 1;
            while(l < r && arr[l] == arr[r]){//删除右边和左边值相等都部分
                r--;
            }
        int ans = INT_MAX;
        while(l <= r){
        
            int mid = ((r - l) >> 1) + l;
            if(arr[mid] == target){//相等
                ans = min(ans, mid);//更新下标
            }
            if(arr[l] <= arr[mid]){//[l,mid]有序
                if(arr[l] <= target && target <= arr[mid]){
                    r = mid - 1;
                }else {
                    l = mid + 1;
                }
            }else {//[mid,r]有序
                if(arr[mid] <=  target && target <= arr[r]){
                    l = mid + 1;
                }else {
                    r = mid - 1;
                }
            }
        }
        return ans == INT_MAX ? -1 : ans;
    }
};

7. Find the minimum value in a rotated array

Corresponding letecode link:

153. Find the minimum value in a rotated sorted array - LeetCode (leetcode-cn.com)

Topic description:

 Problem solving ideas:

We want to find the minimum value in the array. We first use binary to find the value of the middle element and compare it with the last value. If the value of the midpoint is smaller than the value of the last element, let right=mid in the second paragraph, otherwise left =mid+1. Knowing left=mid finds the smallest element. 

Corresponding code:

class Solution {
public:
    int findMin(vector<int>& nums) {
        if(nums.size()==1)//只有一个元素
          return nums[0];
        if(nums[0]<nums.back())//本来就是有序的
          return nums[0];
        int left=0;
        int right=nums.size()-1;
        while(left<right){
            int mid=(left+right)>>1;//取中点
            if(nums[mid]<nums.back()){//说明在第二段
                right=mid;
            }
            else{
                left=mid+1;
            }
        }
        return nums[left];
    }
};

8. Search for minimum value in rotated array II

Corresponding letecode link:

154. Find the minimum value in a rotated sorted array II - LeetCode (leetcode-cn.com)

Topic description

 Problem solving ideas:

The idea of ​​​​this question is basically the same as the previous question, except that there will be equal elements on the left and right, and it will not be possible to determine whether it is on the other side. So we need to delete the part on the right, the value of which is equal to the left value, and the same as the previous question.

For code:

class Solution {
public:
    int findMin(vector<int>& nums) {
           if(nums.size()==1)
             return nums[0];
       
            int left=0;
            int right=nums.size()-1;

            while(left<right&&nums[left]==nums[right])//将相等的部分去除掉
                   right--;
           if(nums[left]<=nums[right])
              return nums[left];
            while(left<right){
                int mid=(left+right)/2;
                if(nums[mid]<nums[0]){//说明在在旋转的拿一部分
                    right=mid;
                }
                else{
                    left=mid+1;
                }
            }
            return nums[left];//返回结果

    }
};

9. Find the local minimum number in an array

Find a local minimum in an array

Topic description:

 Problem solving ideas:

Divide according to the definition of the topic. Please see the code for details:

#include<iostream>
#include<vector>
using namespace std;
int GetMin(vector<int>&arr){
    int n=arr.size();
    //边界条件
    if(arr.size()==1){
        return 0;
    }
    if(arr[0]<arr[1]){
        return 0;
    }
    if(arr[n-1]<arr[n-2]){
        return n-1;
    }
    int left=0;
    int right=n-1;
    while(left<right-1){//剩下两个数最后所以是left<righ-1
        int mid=(left+right)>>1;
        if(arr[mid]<arr[mid-1]&&arr[mid]<arr[mid+1]){//找到了
             return mid;
        }
        else{
            if(arr[mid]>arr[mid-1]){
                right=mid-1;
            }
            else{//arr[mid]>arr[mid+1]找到一边
                left=mid+1;
            }
        }
    }
    return arr[left]<arr[right]?left:right;//比较
    
}
int main(){
    int n;
    cin>>n;
    vector<int>arr(n);
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    cout<<GetMin(arr);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_56999918/article/details/123585575