zoukankan      html  css  js  c++  java
  • 34. Search for a Range

    https://leetcode.com/problems/search-for-a-range/description/

    Given an array of integers sorted in ascending order, 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].

    Sol:

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            
            // ordered sequence. Binary search
            //Time O(logn) Space O(1)
            // implement upper and lower bound function
            
            
            // lower and upper are index elements
            int lower = lower_bound(nums, 0, nums.length, target);
            int upper = upper_bound(nums, 0, nums.length, target);
            
            if (lower == nums.length || nums[lower] != target)
                return new int[]{-1, -1};
            else
                return new int[]{lower, upper - 1};
            
        }
        
        int lower_bound (int[] A, int first, int last, int target){
            while(first != last){
                int mid = first + (last - first) / 2;
                if(target > A[mid]) first = ++ mid;
                else
                    last = mid;
            }
            
            return first;
        }
        
        int upper_bound (int[] A, int first, int last, int target){
            while (first != last){
                int mid = first + (last - first) / 2;
                if (target >= A[mid]) first = ++ mid;
                else
                    last = mid;
            }
            
            return first;
        }
        
    }
     
  • 相关阅读:
    javascript类的封装『转』
    闭包概念
    继承
    理解面向对象
    cookie的使用
    开园啦。。。
    Myslq 之常用命令
    Myslq 之修改提示符
    Myslq 之登陆、退出
    Javascript 之 Number
  • 原文地址:https://www.cnblogs.com/prmlab/p/7390040.html
Copyright © 2011-2022 走看看