zoukankan      html  css  js  c++  java
  • Leetcode704.Binary Search二分查找

    给定一个 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]之间。

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            int high = nums.size() - 1;
            int low = 0;
            while(low <= high)
            {
                int mid = (low + high) / 2;
                if(nums[mid] == target)
                {
                    return mid;
                }
                else if(nums[mid] < target)
                {
                     low = mid + 1;
                }
                else
                {
                    high = mid - 1;
                }
            }
            return -1;
        }
    };
  • 相关阅读:
    死锁
    不能复制文件到服务器
    JWT
    身份验证
    依赖注入
    ml.net
    swift 枚举、结构、类
    nginx 负载均衡
    sql 时间函数大全
    更新SVN时提示要清理,但清理失败,乱码得解决方案
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433997.html
Copyright © 2011-2022 走看看