zoukankan      html  css  js  c++  java
  • LeetCode Search for a Range (二分查找)

    题意

    Given a sorted array of integers, find the starting and ending position of a given target value.
    Your algorithm's runtime complexity must be in the order of O(log n).
    If the target is not found in the array, return [-1, -1].
    For example,
    Given [5, 7, 7, 8, 8, 10] and target value 8,
    return [3, 4].
    给定一个有序数组和一个目标值,查找出目标值在数组中出现的发生下标区域。时间复杂度要求log(N)。

    解法

    刚开始以为下标也需要用二分来查找,但看讨论发现大家都是找出目标值然后再向两边搜索-_-b,这样做的话,最差的情况下(数组里的数全都一样)就是O(N)了,但是也能过。

    class Solution
    {
    public:
        vector<int> searchRange(vector<int>& nums, int target)
        {
    	    int	left = 0;
    	    int	right = nums.size() - 1;
    	    int	index_a = -1;
    	    int	index_b = -1;
    	    int	index = 0;
    	    bool	flag = false;
    
    	    while(left <= right)
    	    {
    		    int	mid = (left + right) >> 1;
    		    if(nums[mid] == target)
    		    {
    			    flag = true;
    			    index = mid;
    			    break;
    		    }
    		    else
    			    if(nums[mid] < target)
    				    left = mid + 1;
    			    else
    				    right = mid - 1;
    	    }
    	    if(flag)
    		    index_a = index;
    	    while(index_a >= 1 && nums[index_a - 1] == target)
    		    index_a --;
    	    if(flag)
    		    index_b = index;
    	    while(index_b < nums.size() - 1 && nums[index_b + 1] == target)
    		    index_b ++;
    
    	    vector<int>	rt = {index_a,index_b};
    	    return	rt;
        }
    };
    
  • 相关阅读:
    PDO预处理语句规避SQL注入攻击
    单例模式
    接口测试框架-[pytest+requests+excel]读取excel表格+requests参数化+pytest测试报告
    git 常用命令
    测试基础
    jmeter 安装
    软件测试常用网址
    MAC下安装配置Tomcat
    python 第六十二章 Django orm 跨表查询
    python 第六十二章 Django cookie和session
  • 原文地址:https://www.cnblogs.com/xz816111/p/5889878.html
Copyright © 2011-2022 走看看