首页 > 代码库 > [Leetcode + Lintcode] 34. Search for a Range
[Leetcode + Lintcode] 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]
.
用binary search轻松解决,search for a range 等同于search for the first/last appearance,只需对常规的binary search 稍作改动,不要一看到等于target就返回index,而是应该根据找first/last来判断是否还要继续做binary search (ex.寻找first appearance时,如果nums[mid] >= target都应该继续binary search,因为找到的index并不一定是first appearance,应该进一步向前寻找直到跳出循环,还应优先判断nums[start]==target是否成立来决定first index)
1. java
public class Solution { public int[] searchRange(int[] nums, int target) { if(nums == null){ return new int[]{-1,-1}; } int start = 0; int end = nums.length - 1; while(start + 1 < end){ int mid = start + (end - start)/2; if(nums[mid] < target){ start = mid; } else if(nums[mid] >= target){ end = mid; } } int[] result = new int[2]; if(nums[start] == target){ result[0] = start; } else if(nums[end] == target){ result[0] = end; } else { return new int[]{-1,-1}; } start = 0; end = nums.length - 1; while(start + 1 < end){ int mid = start + (end - start)/2; if(nums[mid] <= target){ start = mid; } else if(nums[mid] > target){ end = mid; } } if(nums[end] == target){ result[1] = end; return result; } else if(nums[start] == target){ result[1] = start; return result; } return new int[]{-1,-1}; }}
2.Python
class Solution: """ @param A : a list of integers @param target : an integer to be searched @return : a list of length 2, [index1, index2] """ def searchRange(self, A, target): # write your code here result = [-1,-1] if A is None or len(A) == 0: return result start = 0 end = len(A) - 1 while(start + 1 < end): mid = start + (end - start)/2 if A[mid] >= target: end = mid elif A[mid] < target: start = mid if A[start] == target: result[0] = start elif A[end] == target: result[0] = end else: return result start = 0 end = len(A) - 1 while(start + 1 < end): mid = start + (end - start)/2 if A[mid] > target: end = mid elif A[mid] <= target: start = mid if A[end] == target: result[1] = end return result elif A[start] == target: result[1] = start return result return result
[Leetcode + Lintcode] 34. Search for a Range
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。