码迷,mamicode.com
首页 > 其他好文 > 详细

first occurance

时间:2018-02-25 01:10:42      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:hat   find   ret   else   sort   size   move   container   example   

 

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   }

 

first occurance

标签:hat   find   ret   else   sort   size   move   container   example   

原文地址:https://www.cnblogs.com/davidnyc/p/8468093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!