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;
}
}