zoukankan      html  css  js  c++  java
  • 34. Find First and Last Position of Element in Sorted Array (JAVA)

    Given an array of integers nums sorted in ascending order, find the starting and ending position of a given targetvalue.

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

    Example 1:

    Input: nums = [5,7,7,8,8,10], target = 8
    Output: [3,4]

    Example 2:

    Input: nums = [5,7,7,8,8,10], target = 6
    Output: [-1,-1]

    用二分法分别查找最左位置 和最有位置。

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int[] ret = new int[2];
            ret[0] = binaryLeftSearch(nums,target,0,nums.length-1);
            ret[1] = binaryRightSearch(nums,target,0,nums.length-1);
            return ret; 
        }
        
        public int binaryLeftSearch(int[] nums, int target, int left, int right){
            if(left > right) return -1;
            
            int mid = left + ((right-left)>>1);
            int mostLeft;
            if(target <= nums[mid]) {
                mostLeft = binaryLeftSearch(nums,target,left,mid-1);
                if(mostLeft == -1 && target==nums[mid]) mostLeft = mid;
            }
            else{ //target > nums[mid]
                mostLeft = binaryLeftSearch(nums,target,mid+1,right);
            }
            return mostLeft;
        }
        
        public int binaryRightSearch(int[] nums, int target, int left, int right){
            if(left > right) return -1;
            
            int mid = left + ((right-left)>>1);
            int mostRight;
            if(target >= nums[mid]) {
                mostRight = binaryRightSearch(nums,target,mid+1,right);
                if(mostRight == -1 && target==nums[mid]) mostRight = mid;
            }
            else{ //target < nums[mid]
                mostRight = binaryRightSearch(nums,target,left,mid-1);
            }
            return mostRight;
        }
    }
  • 相关阅读:
    在网易和百度实习之后,我才明白了这些事
    从Java小白到收获BAT等offer,分享我这两年的经验和感悟
    曾经做的一个JS小游戏——《Battle City》
    适配器(Adapter)模式
    装饰器(Decorator)模式
    Java IO
    JDBC中驱动加载的过程分析
    从PipedInputStream/PipedOutputStream谈起
    从InputStream到ByteArrayInputStream
    JDK中的动态代理
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10812178.html
Copyright © 2011-2022 走看看