zoukankan      html  css  js  c++  java
  • 704. Binary Search

    !!!题目链接!!!

    solution:

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

    优化:

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            int max = nums.size() - 1;
            int min = 0;
            int mid = 0;
            while(max >= min)
            {
                mid = min + ((max - min) >> 1);
                if (nums[mid] == target)
                {
                    return mid;
                }else if (nums[mid] < target)
                {
                    min = mid + 1;
                }else if (nums[mid] > target)
                {
                    max = mid - 1;   
                }      
            }
            return -1;
        }
    };
    
  • 相关阅读:
    HTTP GET POST PUT DELETE 四种请求
    PHP表达式
    PHP基础
    文件存储
    动态加载布局文件
    Android新增控件
    Spring简介
    Hibenate配置篇
    无题
    struts常用标签与校验器
  • 原文地址:https://www.cnblogs.com/Pomelos/p/15765261.html
Copyright © 2011-2022 走看看