Tricks in decide the index in the binary search with duplicate elements

First Position of Target If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
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) {
        //write your code here
        if(nums.length == 0) return -1;
        
        int start = 0;
        int end = nums.length - 1;
        while (start < end){
            int midIndex = start + (end - start) / 2;
            int mid = nums[midIndex];
            if (target <= mid) {
                end = midIndex;
            } else {
                start = midIndex + 1;
            }
        }
        return nums[start] == target ? start : -1;
    }
}

Because we want to find the first index of the target, we target is equal to the mid, we set end = midIndex (not end = midIndex - 1) to include the possible index into the range. since the while condition is start < end and start is always increasing, there will be no dead loop.

Another example to compare is :

Last Position of Target

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.length == 0) return -1;
        int start = 0;
        int end = nums.length - 1;
        while (start < end){
            int midIndex = start + (end - start)/2 + (end - start)%2;
            int mid = nums[midIndex];
            if(mid <= target){
                start = midIndex;
            }
            else if(mid > target){
                end = midIndex - 1;
            }
        }
        return nums[start] == target ? start : -1;
        
    }
}
using the same idea, when mid == target, start = midIndex (not midIndex + 1) to include the possible answer in the range. However, if start do not move, it is possible that when the gap is 1 (end = start + 1) we will have dead loop. in order to solve that, when computing the mid, we should take the ceilings instead of the floors. Then we ensure mid will always bigger than start and we will not get into dead loop.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值