Eagle233-Blog

[Algorithms] LeetCode 704. 二分查找


Categories Algorithms Array
Tags

108 Words   |   1 Minutes

来源:代码随想录

LeetCode 704. 二分查找

注意区间的写法,我这里是左闭右开。CPP中很多STL容器都是左闭右开的,统一一下写法。

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

        return -1;
    }
};


Page views: Loading...  ·  Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号
Search