zoukankan      html  css  js  c++  java
  • LeetCode: Search for a Range

    Title:

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

    思路:肯定是二分,不过对于查找到那个值之后如何处理呢?可以使用一个全局的min,max值。每次查找到相等的那个值,就更新下min,max。使用递归。

    class Solution {
    public:
        int index_min;
        int index_max;
        Solution(){
            index_min = INT_MAX;
            index_max = -1;
        }
        vector<int> searchRange(vector<int>& nums, int target) {
            vector<int> result;
            int n = nums.size();
            
            search(nums,target,0,n-1);
            if (index_min == INT_MAX && index_max == -1){
                result.push_back(-1);
                result.push_back(-1);
            }else{
                result.push_back(index_min);
                result.push_back(index_max);
            }
            return result;
        }
        void search(vector<int>& nums, int target, int left, int right){
            if (left <= right){
                int m = (left + right)/2;
                if (nums[m] == target){
                    if (m < index_min)
                        index_min = m;
                    if (m > index_max)
                        index_max = m;
                    search(nums,target,left,m-1);
                    search(nums,target,m+1,right);
                }else if (nums[m] > target){
                    search(nums,target,left,m-1);
                }else{
                    search(nums,target,m+1,right);
                }
            }
        }
    };

     如果是求重复元素的次数

    int binarySearchRepeated(vector<int> a, int left, int right, int target){
        if (left > right || a.size() < 1)
            return 0;
        int m = (left + right) / 2;
        if (a[m] == target){
            return 1 + binarySearchRepeated(a,left,m-1,target) + binarySearchRepeated(a,m+1,right,target);
        }else if (a[m] > target){
            return binarySearchRepeated(a,left,m-1,target);
        }else{
            return binarySearchRepeated(a,m+1,right,target);
        }
    }
  • 相关阅读:
    <td>标签clospan和rowspan 可横跨列数和行数
    网线水晶头接法
    安装在墙上的网线接口坏了的处理方法
    php array 数组及数组索引
    php strpos返回字符串首次出现的位置
    escape()、encodeURI()、encodeURIComponent()区别详解
    smarty assign 赋值
    二叉搜索树(搜索二叉树)转换成一个双向链表
    new malloc和delete free 的区别
    两个栈实现一个队列
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4444255.html
Copyright © 2011-2022 走看看