[LeetCode 34]Search for a Range

题目链接: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]. * */public class SearchForARange {//81 / 81 test cases passed.//Status: Accepted//Runtime: 210 ms//Submitted: 0 minutes agopublic int low = Integer.MAX_VALUE;public int high = -1;public int[] searchRange(int[] A, int target) {searchRange(A, 0, A.length – 1, target);if(low != Integer.MAX_VALUE)return new int[]{low, high};elsereturn new int[]{-1, -1};}//二分法查找public void searchRange(int[] A, int left, int right, int target) {if(left <= right) {int mid = (left + right) / 2;if(A[mid] < target) {searchRange(A, mid + 1, right, target);} else if (A[mid] > target) {searchRange(A, left, mid – 1, target);} else {low = Math.min(low, mid);high = Math.max(high, mid);searchRange(A, left, mid – 1, target);searchRange(A, mid + 1, right, target);}}}public static void main(String[] args) {}}

,人,也总是很难发现自己的错误,

[LeetCode 34]Search for a Range

相关文章:

你感兴趣的文章:

标签云: