• 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].

    思路:

    1. 又是二分法

    2. 二分法的框架, 需要考虑的位置有 3 个, 在代码中我标了出来, 分别为 q1, q2, q3

    3. q1 是取 <= 还是取 <. 我的经验是, 若是题目要求找到 target, 那么就用 <=, 否则用 <. 我记得在二分搜索题时, 都是用 < 的

    4. q2 比较容易, 考虑当 low == high 时, 我们希望游标往哪里走

    5. q3, 返回 low/high. q3 的选取与 q2 有关. 还是需要考虑当 low == high 时, 游标会往哪走

    代码

    class Solution {
    public:
        vector<int> searchRange(int A[], int n, int target) {
    		vector<int> res;
    		if(n <= 0)
    			return res;
    
    		int leftIndex = lSearch(A, n, target);
    		int rightIndex = rSearch(A, n, target);
    		
    		res.push_back(leftIndex);
    		res.push_back(rightIndex);
    		return res;
        }
    
    	int lSearch(int A[], int n, int target) {
    		int low = 0, high = n-1;
    		while(low <= high) { // q1
    			int mid = (low+high)>>1;
    			if(A[mid] < target) { // q2
    				low = mid+1;
    			}else{
    				high = mid-1;
    			}
    		}
    		if(A[low] != target)
    			return -1;
    		return low; // q3
    	}
    	int rSearch(int A[], int n, int target) {
    		int low = 0, high = n-1;
    		while(low <= high) { // q1
    			int mid = (low+high)>>1;
    			if(A[mid] > target) { // q2
    				high = mid-1;
    			}else{
    				low = mid +1;
    			}
    		}
    		if(A[high] != target)
    			return -1;
    		return high; // q3
    	}
    };
    

      

  • 相关阅读:
    iOS开发-NSOperation与GCD区别
    FMDB数据库升级
    Xcode自动选择证书
    asp.net常用函数表
    JS操作文件
    Json转换插件
    SpringCloud分布式事务-Seata
    SpringCloud应对高并发的思路
    SpringCloud-Greenwich版本新特性探索(1)---SpringCloudGateway
    如何热更新线上的Java服务器代码
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3510989.html
Copyright © 2020-2023  润新知