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

First Occurrence - Medium

时间:2018-12-16 11:16:45      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:this   examples   pre   col   get   int   integer   ret   ase   

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.

 

time: O(log(n)), space: O(1)

public class Solution {
  public int firstOccur(int[] array, int target) {
    // Write your solution here
    if(array == null || array.length == 0) return -1;
    int left = 0, right = array.length - 1;
    while(left + 1 < right) {
      int mid = left + (right - left) / 2;
      if(array[mid] == target)
        right = mid;
      else if(array[mid] < target)
        left = mid;
      else
        right = mid;
    }
    if(array[left] == target)
      return left;
    else if(array[right] == target)
      return right;
    else
      return -1;
  }
}

 

First Occurrence - Medium

标签:this   examples   pre   col   get   int   integer   ret   ase   

原文地址:https://www.cnblogs.com/fatttcat/p/10125615.html

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