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);
        }
    }
  • 相关阅读:
    编译安装php5 解决编译安装的php加载不了gd
    apache-php
    使用ab对网站进行压力测试
    正则表达式实例 -- 匹配Windows消息宏
    SDK 操作 list-view control 实例 -- 遍历进程
    malloc/free、new/delete 区别
    Python实例 -- 爬虫
    multimap实例 -- 添加、遍历数据
    CListCtrl 扩展风格设置方法---SetExtendedStyle和ModifyStyleEx
    创建指定大小的空文件
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4444255.html
Copyright © 2011-2022 走看看