Algorithm - Binary Search Method / Binary Method (704)

principle:

Taking advantage of the orderliness of the array, the middle point of the search range is taken each time to narrow the search space by half. Compare the intermediate value and the target value until the target value is found or the search interval is empty. 

LeetCode official website - the technology growth platform loved by geeks around the world

topic: 

Given an n-element sorted (ascending) integer array nums and a target value target, write a function to search the target in nums and return the subscript if the target value exists, otherwise return -1.

输入: nums = [-1,0,3,5,9,12], target = 9     
输出: 4       
解释: 9 出现在 nums 中并且下标为 4     

hint:

  • You can assume that all elements in nums are unique.
  • n will be between [1, 10000].
  • Each element of nums will be between [-9999, 9999]

Idea: 

Prerequisites for the binary method: the array is an ordered array and  there are no duplicate elements in the array;

Because once there are duplicate elements, the element subscript returned using the binary search method may not be unique;

Note: Issues with the definition of intervals

The definition of an interval is an invariant . To maintain invariants during the binary search process, every boundary processing during the while search must adhere to the definition of the interval. This is the loop invariant rule.

When writing dichotomy, there are generally two definitions of intervals, left closed and right closed, that is, [left, right], or left closed, right open, that is, [left, right).

Answer: 

Method 1:  Close left and close right [left, right]

      /**
       * @param {number[]} nums
       * @param {number} target
       * @return {number}
       */
      var search = function (nums, target) {
        // right是数组最后一个数的下标,num[right]在查找范围内,是左闭右闭区间
        let mid = 0,
          left = 0,
          right = nums.length - 1;
        // 当left=right时,由于nums[right]在查找范围内,所以要包括此情况
        while (left <= right) {
          mid = Math.floor((left + right) / 2);
          let middleVal = nums[mid];
          // 如果中间数大于目标值,要把中间数排除查找范围,所以右边界更新为mid-1;
          // 如果右边界更新为mid,那中间数还在下次查找范围内
          if (middleVal < target) {
            left = mid + 1;
          } else if (middleVal > target) {
            right = mid - 1;
          } else {
            return mid;
          }
        }
        return -1;
      };

Method 2:  Close left and open right [left, right)

      /**
       * @param {number[]} nums
       * @param {number} target
       * @return {number}
       */
      console.log(new Date().getTime());
      var search = function (nums, target) {
        let mid = 0,
          left = 0,
          right = nums.length;
        while (left < right) {
          mid = Math.floor((left + right) / 2);
          let middleVal = nums[mid];
          if (middleVal < target) {
            left = mid + 1;
          } else if (middleVal > target) {
            right = mid;
          } else {
            return mid;
          }
        }
        return -1;
      };

Video explanation: 

Take you step by step to tear out the correct binary method | Binary search method | Binary search method | LeetCode: 704. Binary search_bilibili_bilibili

Guess you like

Origin blog.csdn.net/qq_38290251/article/details/134920878