Leetcode 34. Search for a Range
Given a sorted array of integers, 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 [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
解题思路:
题意转换, 变成找first bound of target and right bound of target.
找first position:
相同的时候砍掉右边
找last position:
相同的时候砍掉左边
题目可以变化问题:问8(target number)出现了几次?
答案:right bound - left bound + 1
Java code:
public class Solution { public int[] searchRange(int[] nums, int target) { if(nums.length == 0 ){ return new int[]{-1, -1}; } int start, end, mid; int[] bound = new int[2]; //search for left bound start = 0; end = nums.length-1; while (start + 1 < end) { mid = start + (end - start) / 2; if (nums[mid] == target) { end = mid; } else if (nums[mid] < target) { start = mid; } else { end = mid; } } if(nums[start] == target){ bound[0] = start; } else if (nums[end] == target) { bound[0] = end; } else { bound[0] = bound[1] = -1; return bound; } //search for right bound start = 0; end = nums.length-1; while (start + 1 < end) { mid = start + (end - start) / 2; if (nums[mid] == target) { start = mid; } else if (nums[mid] < target) { start = mid; } else { end = mid; } } if(nums[end] == target) { bound[1] = end; }else if (nums[start] == target){ bound[1] = start; }else { bound[0] = bound[1] = -1; return bound; } return bound; } }
Reference:
1. http://www.jiuzhang.com/solutions/search-for-a-range/