zoukankan      html  css  js  c++  java
  • first occurance

    Given a target integer T and an integer array A sorted in ascending order, find the index of the first 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 1

    Corner Cases

    • What if A is null or A of zero length? We should return -1 in this case.
     
     1 public int firstOccur(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     //when left next to right then jump out
     8     //note: first occurance, so if array[mid] == target, should move right, not left
     9     while(left + 1 <right){
    10         int mid = left + (right - left)/2;
    11       if(array[mid] < target){
    12           left = mid ; 
    13       } else{
    14           right = mid ; 
    15       }
    16     }
    17     //post processing: since we need to handle left right not matching while
    18     //first occurance, we check the left first
    19     if(array[left] == target){
    20         return left ; 
    21     }
    22     if(array[right] == target){
    23         return right ; 
    24     }
    25     return -1; 
    26   }
  • 相关阅读:
    在移动端实现常按事件
    HBuilder的一些常用快捷键
    如何在vue里面调用高德地图
    js中获取当前时间
    vux使用方法
    模糊搜索的用法
    Vue-随笔小记
    常用到的一些事件
    java对接东华医疗数据库
    tomcat设置jdk路径
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8468093.html
Copyright © 2011-2022 走看看