[LintCode] 457 Classical Binary Search
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 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步