The road of front-end algorithm to brush questions - binary search

1. Basic concepts

Binary search is based on 有序数组search. First, there are three pointers on the left, middle and right. When 大于the value of the number pointed by the middle pointer, move 小于the right pointer to one place before the middle pointer. .

Code

function finIndex(list, target) {
    
    
  let left = 0,right = list.length - 1,mid;

  while (left <= right) {
    
    
  	mid = Math.floor((right + left) / 2);
    if (list[mid] == target) return mid;
    else if (list[mid] < target) left = mid + 1;
    else if (list[mid] > target) right = mid - 1;
  }

  return -1;
}

Binary search can also solve a class of abstract problems, such as finding [0,0,0,0,0,1,1,1,1,]the position of the first 1 in an array, or the position of the last 0. The code has not changed much compared to the original one, except that the left and right pointers move to the front and rear of the middle pointer.

2. Topic

1. square root of x

square root of x

train of thought

This question is an abstract question of finding the last 0. That is, the previous ones less than or equal to x are recorded as 0, and the ones greater than x are recorded as 1, and the last 0 is the answer to this question.

the code

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    
    
    let left = 0,right = x,mid = Math.floor((left+right)/2);
     // 避免计算超界 mid  = head + ((tail - head) / 2.0);
     
    while(right-left>2){
    
    	//防止死循环
    	mid*mid > x ? right = mid-1 : left = mid
        mid = Math.floor((left+right)/2)
    }

    for(let i=left;i<=right;i++){
    
    	//少于3项用for循环遍历
        if(i*i>x){
    
    
            mid = i-1
            break
        }else{
    
    
            mid = i
        }
    }

    return mid
};

Since the original problem can be regarded as a function f(x)=√x, we can adjust the fixed 100number of times to find the target number. Because every 2-point adjustment will reduce the range to be searched by half, 100 times of 2-point adjustment, the range to be adjusted is 1/100 of 2, and the difference between the left and right pointers is only 1/100 of 2 , and then take the integer part of the left pointer.

var mySqrt = function(x) {
    
    
    let left = 0,right = x,mid;
    right += 1;
    for(let i = 0; i < 100;i++){
    
    
        // 避免计算超界
        mid  = left + ((right - left) /2.0);
        if(mid * mid <= x) left = mid;
        else right = mid;
    }
    return Math.floor(left);
};

Guess you like

Origin blog.csdn.net/m0_49343686/article/details/119542872