当前位置:网站首页>Force buckle 704 Binary search

Force buckle 704 Binary search

2022-06-30 04:56:00 A wise man should not be bald

class Solution {
public:
    int search(vector<int>& nums, int target) {
        // This dichotomy is to put target Put it in a left closed and right closed section , That is to say [left,right] in 
        // So make left The subscript position pointing to the first element of the array , Make right At the position of the subscript of the last element of the array .
        int n = nums.size();
        int left = 0;
        int right = n-1;
        int mid = 0;    // The subscript of the intermediate element , It's defined in while Outside the loop is to avoid frequent creation , Because in while Inside the loop , The beginning of each cycle should be determined mid Size .
        //<= Because left = right It makes sense .
        while(left <= right){
            // amount to mid = (left + right) / 2, Try not to write like this , Because when left and right When the value is large , Adding may cause data overflow .
            mid = (right - left) /2 + left;
            // If at present mid The element value at is exactly equal to target Words , Go straight back to mid
            if(nums[mid] == target){
                return mid;
            }
            // If at present mid The element value at is greater than target Words , Then it means that the target value to be found is mid The left side of the , So will right-1
            else if(nums[mid] > target){
                right = mid - 1;
                continue;
            }
            // If at present mid Element value at is less than target Words , Then it means that the target value to be found is mid The right side of the , So will left-1
            else{
                left = mid + 1;
                continue;
            }
        }
        // This situation indicates that the target value is not nums Array , So back -1
        return -1;
    }
    // Time complexity :O(logn), among  n  Is the length of the array .
    // Spatial complexity :O(1).
};

原网站

版权声明
本文为[A wise man should not be bald]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/181/202206300445040060.html