zoukankan      html  css  js  c++  java
  • 【leetcode】Search for a Range(middle)

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

    思路:

    我自己用了个最简单的,普通的二分查找,然后两边延伸找起始和结束点。

    int *searchRange(int A[], int n, int target) {
        int ans[2] = {-1, -1};
        int l = 0, r = n - 1;
        while(l <= r)
        {
            int m = (l + r) / 2;
            if(A[m] == target)
            {
                ans[0] = ans[1] = m;
                while(ans[0] - 1 >= 0 && A[ans[0]] == A[ans[0] - 1]) ans[0]--;
                while(ans[1] + 1 < n && A[ans[1]] == A[ans[1] + 1]) ans[1]++;
                return ans;
            }
            else if(A[m] > target)
                r = m - 1;
            else
                l = m + 1;
        }
        return ans;
    }

    大神分成了分别用两次二分查找找起始和结束位置

    https://leetcode.com/discuss/18242/clean-iterative-solution-binary-searches-with-explanation中有详细解释

    vector<int> searchRange(int A[], int n, int target) {
        int i = 0, j = n - 1;
        vector<int> ret(2, -1);
        // Search for the left one
        while (i < j)
        {
            int mid = (i + j) /2;
            if (A[mid] < target) i = mid + 1;
            else j = mid;
        }
        if (A[i]!=target) return ret;
        else ret[0] = i;
    
        // Search for the right one
        j = n-1;  // We don't have to set i to 0 the second time.
        while (i < j)
        {
            int mid = (i + j) /2 + 1;   // Make mid biased to the right
            if (A[mid] > target) j = mid - 1;  
            else i = mid;               // So that this won't make the search range stuck.
        }
        ret[1] = j;
        return ret; 
    }

    另一种通过加减0.5来找位置的方法

    class Solution:
    # @param A, a list of integers
    # @param target, an integer to be searched
    # @return a list of length 2, [index1, index2]
    def searchRange(self, arr, target):
        start = self.binary_search(arr, target-0.5)
        if arr[start] != target:
            return [-1, -1]
        arr.append(0)
        end = self.binary_search(arr, target+0.5)-1
        return [start, end]
    
    def binary_search(self, arr, target):
        start, end = 0, len(arr)-1
        while start < end:
            mid = (start+end)//2
            if target < arr[mid]:
                end = mid
            else:
                start = mid+1
        return start
  • 相关阅读:
    使用getopts处理Shell脚本参数
    SAP R/3 MM模块学习笔记
    应 阿成1 要求 co主要业务操作手册
    AIX磁盘管理命令
    工作中心和工艺路线
    顾问学院培训教材 TAMM ,TAPP,TASD,TACO
    十个“三角形”汉字,好看、不好认
    ALV做出的报表里更改布局里没有保存按钮的解决方法
    SAP系统内的发票校验
    修改SAP 登录后的背景图片
  • 原文地址:https://www.cnblogs.com/dplearning/p/4359737.html
Copyright © 2011-2022 走看看