二分查找法


leetcode 704. 二分查找

给定一个 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

提示:

  1. 你可以假设 nums 中的所有元素是不重复的。
  2. n 将在 [1, 10000]之间。
  3. nums 的每个元素都将在 [-9999, 9999]之间。
 1 #include 
 2 #include 
 3 using namespace std;
 4 
 5 class Solution
 6 {
 7 public:
 8     int search(vector<int> &nums, int target) {
 9         int size = nums.size();
10         int left = 0;
11         int right = size - 1;
12         while (left <= right) {
13             int mid = (left + right) / 2;
14             if (target == nums[mid]) {
15                 return mid;
16             }
17             if (target > nums[mid]) {
18                 left = mid + 1;
19             } else {
20                 right = mid - 1;
21             }
22         }
23         return -1;
24     }
25 };
26 
27 int main()
28 {
29     Solution *test = new Solution();
30     // 测试数组中存在目标元素
31     vector<int> vec = {-1, 0, 3, 5, 9, 12};
32     int target = 9;
33     int indext = test->search(vec, target);
34     std::cout << "index:" << indext << endl; // index:4
35     // 测试数组中不存在目标元素
36     vec = {-1, 0, 3, 5, 9, 12};
37     target = 2;
38     indext = test->search(vec, target);
39     std::cout << "index:" << indext << endl; // index:-1
40 
41     delete test;
42     system("pause");
43     return 0;
44 }

运行结果:

相关