zoukankan      html  css  js  c++  java
  • last occurance

    Given a target integer T and an integer array A sorted in ascending order, find the index of the last occurrence of T in A or return -1 if there is no such index.

    Assumptions

    • There can be duplicate elements in the array.

    Examples

    • A = {1, 2, 3}, T = 2, return 1
    • A = {1, 2, 3}, T = 4, return -1
    • A = {1, 2, 2, 2, 3}, T = 2, return 3

    Corner Cases

    • What if A is null or A is array of zero length? We should return -1 in this case.
     1 public int lastOccur(int[] array, int target) {
     2     // Write your solution here
     3     if(array == null || array.length == 0 ){
     4         return -1 ; 
     5     }
     6     int left = 0, right = array.length -1 ; 
     7     while(left + 1 <right){
     8         int mid = left + (right - left)/2 ; 
     9       //因为找最后的,所以碰上也不扔着,带着往后面找
    10       if(array[mid]<=target){
    11           left = mid ; 
    12       } else{
    13           right = mid ; 
    14       }
    15     }
    16     //post processing
    17     if(array[right] == target){
    18         return right ; 
    19     }
    20     if(array[left] == target){
    21         return left; 
    22     }
    23     return -1 ; 
    24   }
  • 相关阅读:
    day 17
    day 16
    信息系统项目管理师 教程学习 第一章
    服务器安全防护
    少有人走的路
    Python文件学习
    测试新文章
    测试
    python基础 一、 数值类型、序列类型和散列类型
    apache No input filespecified
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8468142.html
Copyright © 2011-2022 走看看