LintCode 14---二分查找

public class Solution {
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    public int binarySearch(int[] nums, int target) {
         int left = 0,right = nums.length-1;
            int mid = (left + right) / 2;
            while (left < right) {
                if (nums[mid] < target) left = mid + 1;
                if (nums[mid] >= target) right = mid;
                mid = (left + right) / 2;
            }
            return nums[mid] == target ? mid : -1;
    }
}

 

上一篇:LintCode 35---翻转链表


下一篇:在我的android应用中实现zxing-2.0