Description
Find any 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 1 or 2.
For target = 5, return 4 or 5.
For target = 6, return -1.
4/27/2017
算法班
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 findPosition(int[] nums, int target) { 8 // Write your code here 9 if (nums == null || nums.length == 0) { 10 return -1; 11 } 12 13 int start = 0, end = nums.length - 1; 14 while (start + 1 < end) { 15 int mid = start + (end - start) / 2; 16 17 if (nums[mid] <= target) { 18 return mid; 19 } else if (nums[mid] < target) { 20 start = mid; 21 } else { 22 end = mid; 23 } 24 } 25 if (nums[start] == target) return start; 26 else if (nums[end] == target) return end; 27 return -1; 28 } 29 }