lc34 Find First and Last Position of Element in Sorted Array

https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

[brainstorm] this solution fail in 35min, fail on corner case
1 use binary
2 find last 8, say target=8
3 find first 8,
then findLast, findFirst be 2 methods, can we just use 1 method?
4 instead to find first 8, find last 7
4 what problem will appear?

what bug is in below code?

[brainstorm] this solution AC in 10min
1 use binary
2 find last
3 find first

[code]

class Solution {
    public int[] searchRange(int[] nums, int target) {

        int n = nums.length;
        if(n==0){
            return new int[]{-1, -1};
        }         
        int begin = binFirst(nums, 0, n-1, target);
        int end = binLast(nums, 0, n-1, target);

        if(end==-1){
            return new int[]{-1, -1};
        }       
        return new int[]{begin, end};

    }

    int binLast(int[] nums, int l, int r, int target){
        
        while(l<r){
            int m = l + (r-l+1)/2;
            if(nums[m]<=target){
                l = m;
            }
            else if(nums[m]>target){
                r = m -1;
            }
        }
        return nums[l]==target?l:-1;
    }

    int binFirst(int[] nums, int l, int r, int target){
        
        while(l<r){
            int m = l+(r-l)/2;
            if(nums[m]>=target){
                r = m;
            }
            else if(nums[m]<target){
                l = m+1;
            }
        }
        return nums[l]==target?l:-1;
    }
}

[bug code]

class Solution {
    public int[] searchRange(int[] nums, int target) {

        int n = nums.length;
        if(n==0){
            return new int[]{-1, -1};
        }
         
        int begin = bin(nums, 0, n-1, target-1);
        int end = bin(nums, 0, n-1, target);

        if(end==-1){
            return new int[]{-1, -1};
        }       
        return new int[]{begin+1, end};

    }

    int bin(int[] nums, int l, int r, int target){
        
        while(l<r){
            int m = l + (r-l+1)/2;
            if(nums[m]<=target){
                l = m;
            }
            else if(nums[m]>target){
                r = m -1;
            }
        }
        return nums[l]==target?l:-1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值