zoukankan      html  css  js  c++  java
  • [LintCode] Last Position of Target

    Find the last position of a target number in a sorted array. Return -1 if target does not exist.

    Example

    Given [1, 2, 2, 4, 5, 5].

    For target = 2, return 2.

    For target = 5, return 5.

    For target = 6, return -1.

     1 public class Solution {
     2     /*
     3      * @param nums: An integer array sorted in ascending order
     4      * @param target: An integer
     5      * @return: An integer
     6      */
     7     public int lastPosition(int[] nums, int target) {
     8         if(nums == null || nums.length == 0) {
     9             return -1;
    10         }
    11         int low = 0, high = nums.length - 1;
    12         while(low + 1< high) {
    13             int mid = low + (high - low) / 2;
    14             if(nums[mid] == target) {
    15                 low = mid;
    16             }
    17             else if(nums[mid] > target) {
    18                 high = mid - 1;
    19             }
    20             else {
    21                 low = mid + 1;
    22             }
    23         }
    24         if(nums[high] == target) {
    25             return high;
    26         }
    27         else if(nums[low] == target) {
    28             return low;
    29         }
    30         return -1;
    31     }
    32 }

    Related Problems

     First Position of Target

  • 相关阅读:
    3-8
    3-7
    3-5
    3-4
    3-3
    3-2
    3-1
    2-11
    2-10
    2-9
  • 原文地址:https://www.cnblogs.com/lz87/p/7494157.html
Copyright © 2011-2022 走看看