Last Occurrence - Medium
Posted fatttcat
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Last Occurrence - Medium相关的知识,希望对你有一定的参考价值。
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.
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; } }
以上是关于Last Occurrence - Medium的主要内容,如果未能解决你的问题,请参考以下文章
Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)(示例代