算法刷题--二分查找

Day 1

Code 1 : Binary Search

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Solution

class Solution {
public:
   int search(vector<int>& nums, int target) {
   	int l=0;
   	int r=nums.size()-1;
   	int i=0;
   	while ((l<=r) &&(r<=nums.size())) {
   		i=(l+r)/2;
   		if (nums[i]==target)
   			return i;
   		else if (nums[i]<target){
   			l=i+1;
   		}
   		else{
   			r=i-1;
   		}	
   	}

   	return -1;
   }
};
  • 二分查找循环的两个条件 :左<右,右<总数。
  • 不用特意判断左右端点是否取到target,一直用中间值判断即可。

Code 2 : First Bad Version

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example 1:

Input: n = 5, bad = 4
Output: 4

Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

Solution

class Solution {
public:
    int firstBadVersion(int n) {
        int l=1;
        int r=n;
        while (l<=r && r<=n){
		    int i=l+(r-l)/2;
		    if (isBadVersion(i)){
		    	if(!isBadVersion(i-1)){
		    		return i;
				}
				else{
					r=i-1;
				}
			}
			else{
				l=i+1;
			}
		}
        return -1;
    }
};
  • 使用二分搜索
  • 注意防止溢出的方法 :i=l+(r-l)/2

Code 3 : Search Insert Position

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Example 1

Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3

Input: nums = [1,3,5,6], target = 7
Output: 4

Example 4

Input: nums = [1,3,5,6], target = 0
Output: 0

Example 5:

Input: nums = [1], target = 0
Output: 0

Solution

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
		int l=0;
		int r=nums.size()-1;
		while (l<=r){
			int i=l+(r-l)/2;
            if (nums[i]==target)
                return i;
			else if (nums[i]>=target)
				r=i-1;
			else 
				l=i+1;
		}
		return l;
    }
};
  • 套用二分查找模板
	int searchInsert(vwctor<int> nums , int target) {
        int left = 0, right = nums.size() - 1; // 注意 总数减一
        while(left <= right) { // 注意 小于等于
            int mid = (left + right) / 2; // 注意 也可以用防溢出写法
            if(nums[mid] == target) { 
                // 相关逻辑
            } else if(nums[mid] < target) {
                left = mid + 1; // 注意
            } else {
                right = mid - 1; // 注意
            }
        }
        // 相关返回值
        return 0;
    }
  • 最后返回了l值,表示如果找不到返回的下标。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值