[Leetcode learning] binary search application

Source: Internet
Author: User

More follow my hexo blog: http://jasonding1354.github.io/

Home: http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles

Binary Search

Binary Search is a search algorithm used to search for a specific element in an ordered array. The search process starts from the intermediate element of the array. If the intermediate element is the element to be searched, the search process ends. If a specific element is greater than or less than the intermediate element, search in the half where the array is greater than or less than the intermediate element, and compare it from the intermediate element as before. If the array in a step is empty, it indicates that no value can be found. This search algorithm reduces the search range by half for each comparison. Half-fold search reduces the search area by half each time, and the time complexity is logn ).
The advantage of binary lookup is that the number of queries is small, the search speed is fast, and the average performance is good. The disadvantage is that the table to be queried must be an ordered table, and it is difficult to insert or delete the table. Therefore,Binary Search is a method for finding the optimal solution of a problem by constantly narrowing down the possible scope of the solution. It is suitable for searching frequently ordered lists without frequent changes..

Binary Search Algorithm requirements
  1. Sequential storage structure is required
  2. Ordered by keyword size
Binary Search Algorithm Flowchart
Binary Search flowchart Binary Search C source code
// Recursive version of Binary Search int binary_search_recursion (const int array [], int low, int high, int key) {int mid = low + (high-low)/2; if (low> high) Return-1; else {If (array [Mid] = Key) return mid; else if (array [Mid]> key) return binary_search_recursion (array, low, mid-1, key); else return binary_search_recursion (array, Mid + 1, high, key );}} // The cyclic version of Binary Search int binary_search_loop (const int array [], int Len, int key) {int low = 0; int high = len-1; int mid; while (low <= high) {mid = (low + high)/2; If (array [Mid] = Key) return mid; else if (array [Mid]> key) High = mid-1; else low = Mid + 1;} return-1 ;}
Boundary error

The boundary of the binary search algorithm is generally divided into two types: Left closed and right open intervals, such as [low, high) and left closed and right closed intervals, such as [low, high]. Note that the initialization conditions of the circulating body in vitro must comply with the same interval rules as those of the circulating body. That is to say, if the cyclic body is initialized, it is based on the left closed and right open intervals, so the internal iteration of the loop body should also be like this.

Leetcode instance search in rotated sorted array requirements

Suppose a sorted array is rotated at some unknown to you beforehand
Suppose there is a sorted array, which is rotated at a certain axis point in advance.
(I. e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2)
You are given a target value to search.
If found in the array return its index, otherwise return-1.
You may assume no duplicate exists in the array.

Analysis

Binary Search, the difficulty lies in the determination of the left and right boundary
If a [Middle] <= A [first], the subarray of the [Middle, last-1] interval is an ascending sequence, then it can be queried using the binary search method; otherwise, it will be further divided until the sub-array is an incremental array. The opposite is true.
Since last always points to the next position of the last element of the sub-array, you should pay special attention to the value assignment in the program.

C ++ code
class Solution {public:    int search(int A[], int n, int target) {        int first = 0;        int last = n;        while(first != last)        {            int middle = (first + last)/2;            if(A[middle] == target)                return middle;            if(A[first] >= A[middle]){                if(target > A[middle] && target <= A[last-1])                    first = middle+1;                else                    last = middle;            }            else            {                if(target < A[middle] && target >= A[first])                    last = middle;                else                    first = middle+1;            }        }        return -1;    }};
Search in rotated sorted array II Requirements

Follow Up For "search in rotated sorted array": What if duplicates are allowed?
Write a function to determine if a given target is in the array.
As a variant of the previous question, this question allows repeated Elements

Analysis

If repeated elements are allowed, if a [Middle]> = A [left] in the previous question, the assumption that [left, middle] is an incremental sequence cannot be true, for example, [1, 3, 1, 1].
If a [m]> = A [l] is not necessarily incremental, split it into two conditions:

  • If a [m]> A [L], the interval [l, m] increases progressively.
  • If a [m] = A [l] cannot be determined, then l ++. Let's take a look at it. C ++ code
    class Solution {public:  bool search(int A[], int n, int target) {      int first = 0,last = n;      while(first != last)      {          int mid = (first+last)/2;          if(A[mid] == target)              return true;          if(A[mid] == A[first])              first++;          else if(A[mid] > A[first])          {              if(A[first]<= target && A[mid] > target)                  last = mid;              else                  first = mid+1;          }          else          {              if(A[mid] < target && A[last-1] >= target)                  first = mid+1;              else                  last = mid;          }      }      return false;  }};
Application of the Binary Search idea to find the optimal solution

The binary search method is also useful in finding the optimal solution. For example, the question of "Finding the smallest X that meets a certain condition C (x. For any X that satisfies C (x), if all X '> = x also satisfies C (X'), the minimum X can be obtained by binary search.
First, we initialize the left endpoint of the range to a value that does not meet C (x), and the right endpoint to a value that meets C (X. Then, the midpoint mid = (Lb + UB)/2 is selected each time to determine whether C (MID) meets the requirements and narrow down the scope until (LB, UB] is small enough. At last, UB is the minimum value.
Similarly, the maximization problem can be solved in the same way.

Assume a solution and determine whether it is feasible

There are n ropes with the length of Li. If K ropes of the same length are cut from them, how long can each of these ropes be? The answer is retained to the second decimal point.
Restrictions:

  • 1 <= n <= 10000
  • 1 <= k <= 10000
  • 1 <= LI <= 100000
Analysis

If the condition is C (x) =, K ropes with x length can be obtained.
Then the problem is solved by finding the largest X that meets the C (x) condition. When the interval is initialized, the lower bound is lB = 0 and the upper bound is UB = inf.
Conversion:
Because the rope with the length of Li can cut the rope with the floor (Li/x) segment length of X at most
C (x) = (whether the sum of floor (Li/X) is greater than or equal to K)

Code instance
#include <iostream>#include <math.h>using namespace std;#define MAX_N 10int N = 4;int K = 10;double L[MAX_N] = {8.02,7.43,4.57,5.39};bool C(double x){    int num = 0;        for(int i=0;i<N;i++)    {        num += (int)(L[i]/x);    }    return num >= K;}void solve(){    double lb = 0;    double ub = 1000;    for(int i=0;i<100;i++)    {        double mid = (lb+ub)/2;        if(C(mid)) lb = mid;        else ub = mid;    }    cout << floor(ub*100)/100<<endl;}int main() {    solve();    return 0;}
End Determination of Binary Search

Generally, the allowed error range or the number of digits after the decimal point in the output is specified. It is necessary to set reasonable end conditions to meet the precision requirements.
In the above procedure, we set the number of cycles as the condition for termination. The range of one cycle can be reduced by half, and the precision range of 100 cycles can reach the power of 10-30, basically no problem.

Maximum Average Value

The weight and value of N items are WI and VI. K items are selected to maximize the value per unit of weight.
Restrictions:

  • 1 <= k <= n <= 10 ^ 4
  • 1 <= WI, VI <= 10 ^ 6
Analysis
Maximized average code instance
//inputint n,k;int w[MAX_N],v[MAX_N];double y[MAX_N];// v - x * wbool C(double x){    for(int i=0;i<n;i++){        y[i] = v[i] - x*w[i];    }    sort(y,y+n);    //compute the sum of top-k number(array y)    double sum = 0;    for(int i=0;i<k;i++){        sum+=y[n-i-1];    }    return sum >= 0;}void solve(){    double lb=0,ub=INF;    for(int i=0;i<100;i++){        double mid = (lb+ub)/2;        if(C(mid))            lb = mid;        else            ub = mid;    }    printf("%.2f\n",ub);}

[Leetcode learning] binary search application

Related Article

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.