Search for a Range
01/16/2018 update
Solution with current chosen template. Longer but much safer. Note that when finding upper bound, check r index first.
Problem:
Solution with current chosen template. Longer but much safer. Note that when finding upper bound, check r index first.
class Solution { public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[]{-1, -1}; } int start = -1, end = -1; int low = 0, high = nums.length - 1; while (low + 1< high) { int mid = low + (high - low)/2; if (nums[mid] >= target){ high = mid; } else { low = mid; } } if (nums[low] == target) start = low; else if (nums[high] == target) start = high; else return new int[]{-1, -1}; low = 0; high = nums.length - 1; while (low + 1< high) { int mid = low + (high - low)/2; if (nums[mid] <= target){ low = mid; } else { high = mid; } } if (nums[high] == target) end = high; else if (nums[low] == target) end = low; else return new int[]{-1, -1}; return new int[]{start, end}; } }---------------------------------------------------------------------------------------------------------------------
Problem:
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return
[-1, -1]
.
For example,
Given
return
Given
[5, 7, 7, 8, 8, 10]
and target value 8,return
[3, 4]
.
Analysis:
Binary search's capability has been extended by this problem. Use binary search to find lower bound and upper bound separately.
lower bound: midValue >= target go left (hi = mid)
upper bound: midValue <= target go right (lo = mid + 1)
Solution:
class Solution { public int[] searchRange(int[] nums, int target) { int lo = findBoundry(nums, target, true); int hi = findBoundry(nums, target, false) - 1; if (lo == nums.length || nums[lo] != target) return new int[]{-1, -1}; else return new int[]{lo, hi}; } private int findBoundry(int[] nums, int target, boolean left) { int low = 0, high = nums.length; while (low < high) { int mid = low + (high - low)/2; if (nums[mid] > target || (left && nums[mid] == target)){ high = mid; } else { low = mid + 1; } } return low; } }
评论
发表评论