while i was solving the question on leetcode which says in an Given array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. so it was impossible to return the starting and ending of a target element in an array with simple binary scarch because it only returns the index where it found the first target element that can be anything first , end or middle of that element. so we use Double Binary Scarch , and here's how to do it ...
First Binary Search:
Second Binary Search:
Return Result:
Time Complexity:
Space Complexity:
class Solution { public int[] searchRange(int[] nums, int target) { int ei = nums.length - 1; int si = 0; int[] res = {-1, -1}; // Initialize result array // First binary search to find the last occurrence while (si <= ei) { int mid = si + (ei - si) / 2; if (target < nums[mid]) { ei = mid - 1; } else if (target > nums[mid]) { si = mid + 1; } else { res[1] = mid; // Update end index si = mid + 1; // Search in the right half } } // Reset the pointers for the second binary search si = 0; ei = nums.length - 1; // Second binary search to find the first occurrence while (si <= ei) { int mid = si + (ei - si) / 2; if (target < nums[mid]) { ei = mid - 1; } else if (target > nums[mid]) { si = mid + 1; } else { res[0] = mid; // Update start index ei = mid - 1; // Search in the left half } } return res; // Return the result array } }
The above is the detailed content of How to use Advanced Binary Scarch ?. For more information, please follow other related articles on the PHP Chinese website!