[Data Structure and Algorithm Series 1] Binary Search

Given an nordered (ascending) integer array of elements numsand a target value target, write a function to search for nums, targetand return the subscript if the target value exists, otherwise return -1.

Example 1:

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

Example 2:

输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1

hint:

  1. You can assume that numsall elements in are unique.
  2. nwill be in [1, 10000]between.
  3. numsEach element of will be [-9999, 9999]between.

Parse:

Prerequisites for using dichotomy:

  • Array is an ordered array
  • no duplicate elements in the array

C++Code:

# include <iostream>
# include <vector>
using namespace std;


int search(vector<int>& nums, int target) {
	int left = 0;
	int right = nums.size() - 1;
	while (left <= right) {
		int middle = left + ((right - left) / 2);
		if (nums[middle] > target) {
			right = middle - 1;
		}
		else if (nums[middle] < target) {
			left = middle + 1;
		}
		else {
			return middle;
		}
	}
	
}

int main() {
	vector<int> nums = { 1, 2, 3, 4, 5, 9, 10, 12 };
	int target = 2;
	
	int result = search(nums, target);
	std::cout << "subscript of target: " << result << std::endl;

	return 0;
}

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-7Rxb4oxx-1693232694708) (E:\Work\Algorithm Brushing Notes\Data Structure and Algorithm.assets\image- 20230828221424550.png)]

pythonCode:

def search(nums, target):
    left = 0
    right = len(nums) - 1

    while(left <= right):
        middle = left + ((right - left) // 2)
        if nums[middle] > target:
            right = middle - 1
        elif(nums[middle] < target):
            left = middle + 1
        else:
            return middle
        
nums = [1 ,2, 3, 4, 5, 6, 7, 9, 11]
target = 9
print(f"subscript of target: {
      
      search(nums, target)}")

insert image description here

Guess you like

Origin blog.csdn.net/qq_43456016/article/details/132549453