首页 > 其他 > 详细

First Position of Target

时间:2017-02-12 14:27:01      阅读:218      评论:0      收藏:0      [点我收藏+]

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1.

分析

找排序数组某个数字的右边界
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    /**
     * @param nums: An integer array sorted in ascending order
     * @param target: An integer
     * @return an integer
     */
    public int lastPosition(int[] nums, int target) {
        // Write your code here
        if(nums == null || nums.length == 0)
            return -1;
        int left = 0, right = nums.length -1, mid;
        while(left < right){
            mid = left + (right - left + 1) / 2;//insure when right is 1 bigger than left, mid eaqual to right 
            if(nums[mid] > target){
                right = mid - 1;
            }
            else{
                left = mid;
            }
        }
        if(nums[right] == target)
            return right;
        else
            return -1;
    }
}





First Position of Target

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

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