首页 > 其他 > 详细

Classical Binary Search

时间:2017-02-12 14:28:44      阅读:197      评论:0      收藏:0      [点我收藏+]
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

原文:http://www.cnblogs.com/zhxshseu/p/b40a2a8739a00d055d248b35db5a0cb8.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!