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;
        }
    }
  • 相关阅读:
    最火的.NET开源项目[转]
    ExtJs4.1目录结构介绍和使用说明[转]
    mvc4 Forms验证存储 两种登录代码
    微服务 第九章 springboot 使用NoSql数据库:redis
    【数据挖掘】关联分析之Apriori(转载)
    C语言面试
    10.15习题2
    java 执行linux命令
    servlet tomcat eclipse
    002_监测ssl证书过期时间
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10812178.html
Copyright © 2011-2022 走看看