JAVA 2 binary searches log(n) runtime


  • 0
    I
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            
            int left = 0, right = nums.length - 1;
            int lp = -1, rp = -1;
            
            while(left <= right) {
                int mid = left + (right - left) / 2;
                if(nums[mid] == target) {
                    if(mid == 0 || nums[mid - 1] != target) {
                        lp = mid;
                        break;
                    }
                    
                    right = mid - 1;
                } else if(nums[mid] > target) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            
            left = 0; right = nums.length - 1;
            while(left <= right) {
                int mid = left + (right - left) / 2;
                if(nums[mid] == target) {
                    if(mid == nums.length - 1 || nums[mid + 1] != target) {
                        rp = mid;
                        break;
                    }
                    
                    left = mid + 1;
                } else if(nums[mid] > target) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            
            return new int[]{lp, rp};
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.