code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

Indexoflastoccurrance

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

class IndexOfLastOccurrance {

  static int func(int[] nums, int target) {
    int start = 0;
    int end = nums.length - 1;
    while(start < end){
      int mid = (start + end)/2;
      if(nums[mid] > target) {
        end = mid - 1;
      } else if(nums[mid] < target) {
        start = mid + 1;
      } else {
        if(mid == nums.length - 1 || nums[mid] != nums[mid + 1]){
          return mid;
        } else {
          start = mid + 1;
        }
      }
    }
    return -1;
  }

  public static void main(String[] args){
    int[] nums = new int[] { 1, 4, 8, 34, 34, 34, 123, 123, 3466, 5687 };
    int result = func(nums, 34);
    System.out.println(result);
  }
}

Created 2021-12-21T23:25:36+00:00, updated 2021-12-22T00:13:04+00:00 · History · Edit