C/C++教程

LeetCode 704 Binary Search 模板

本文主要是介绍LeetCode 704 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.

Solution

点击查看代码
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        if(n==1){
            if(nums[0]==target)return 0;
            else return -1;
        }
        int l=0,r=n-1;
        int mid;
        while(l<r){
            mid = (l+r)>>1;
            if(nums[mid]<target)l=mid+1;
            else if(nums[mid]==target)return mid;
            else r=mid;
        }
        if(nums[r]!=target)return -1;
        else return r;
    }
};
这篇关于LeetCode 704 Binary Search 模板的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!