---
# System prepended metadata

title: Leetcode 704. Binary Search
tags: [Leetcode(C++)]

---

# Leetcode 704. Binary Search
###### tags: `Leetcode(C++)`

題目 : https://leetcode.com/problems/binary-search/ 。

想法 : 模擬二分搜，難處在邊界判斷。

時間複雜度 : O(logn)。

程式碼 :

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