Classical Binary Search
Posted copperface
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Classical Binary Search相关的知识,希望对你有一定的参考价值。
Find any position of a target number in a sorted array. Return -1 if target does not exist.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Solution { /** * @param nums: An integer array sorted in ascending order * @param target: An integer * @return an integer */ public int findPosition( int [] nums, int target) { // Write your code here if (nums == null || nums.length == 0) return -1; int left = 0, right = nums.length - 1; while (left < right){ int mid = left + (right - left) / 2; if (nums[mid] < target) left = mid + 1; else right = mid; } if (nums[right] == target) return right; return -1; } } |
以上是关于Classical Binary Search的主要内容,如果未能解决你的问题,请参考以下文章
面试代码基础二分法binary Search Sorted Array