BinarySearch[5]34. Find First and Last Position of Element in Sorted Array

Thoughts:
The main problem , is to solve the condition that mid == target.
If mid == target, we need find the range of the target.
So how to find the range of the target?

1.Binary Search Solution1

Problem: too many codes.

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] targetRange = {-1, -1};
        if(nums == null || nums.length == 0) return targetRange;
        
        int start = 0, end = nums.length-1;
        while(start + 1 < end){
            int mid = start + (end - start)/2;
            if(nums[mid] == target){
                //the key is to find the start and end of the range
                start = mid;
                end = mid;
                while(start >0 && nums[start] == nums[start-1]){
                    -- start;
                }
                while(end< nums.length-1 && nums[end] == nums[end+1]){
                    ++ end;
                }
                targetRange[0] = start;
                targetRange[1] = end;
                return targetRange;
                
            }else if(nums[mid] > target){
                end = mid;
            }else{
                start = mid;
            }
        }
        
        if(nums[start] == target && nums[end] == target){
            targetRange[0] = start;
            targetRange[1] = end;
            return targetRange;
        }
        if(nums[start] == target && nums[end] != target){
            targetRange[0] = start;
            targetRange[1] = start;
            return targetRange;
        }
        if(nums[start] != target && nums[end] == target){
            targetRange[0] = end;
            targetRange[1] = end;
            return targetRange;
        }
        
        return targetRange;
    }
}

2.Binary Search Solution2

Improve the codes.
Thoughts:

  • find start and end separately.
  • find start point: 移动end指针使得end往左走,找到start。
    • if (nums[mid] >= target), end = mid;
    • else start = mid;
  • find end point:移动start指针使得start往右走,找到end。
    • if(nums[mid] > target) end = mid;
    • else start = mid;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值