标签:ast pre null log index tar style nbsp duplicate
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
Corner Cases
time: O(log(n)), space: O(1)
public class Solution { public int lastOccur(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) left = mid; else if(array[mid] > target) right = mid; else left = mid; } if(array[right] == target) return right; else if(array[left] == target) return left; else return -1; } }
标签:ast pre null log index tar style nbsp duplicate
原文地址:https://www.cnblogs.com/fatttcat/p/10125617.html