# 704.Binary Search

**704.Binary Search**

难度:Easy

> 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。

示例 1:

输入: nums = \[-1,0,3,5,9,12], target = 9 输出: 4 解释: 9 出现在 nums 中并且下标为 4 示例 2:

输入: nums = \[-1,0,3,5,9,12], target = 2 输出: -1 解释: 2 不存在 nums 中因此返回 -1

提示：

你可以假设 nums 中的所有元素是不重复的。 n 将在 \[1, 10000]之间。 nums 的每个元素都将在 \[-9999, 9999]之间。

二分查找，需要注意边界情况，以及循环终止条件。

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

> 执行用时 :88 ms, 在所有 C++ 提交中击败了21.54%的用户\
> 内存消耗 :10.9 MB, 在所有 C++ 提交中击败了70.73%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/704.binary_search.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
