欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-01-17 22:11:34
...

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;