原题链接:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
难度:medium
简单的binary search
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums == null || nums.length == 0) return new int[] {-1, -1};
int result[] = new int[] {-1, -1};
search(nums, target, 0, nums.length - 1, result);
return result;
}
public void search(int[] nums, int target, int s, int e, int[]result) {
int m = (s + e) / 2;
if(nums[m] == target) {
if(m > result[1] || result[1] == -1) {
result[1] = m;
}
if(m < result[0] || result[0] == -1) {
result[0] = m;
}
}
if(s >= e) {
return;
}
if(nums[m] >= target) {
search(nums, target, s, m, result);
}
if(nums[m] <= target) {
search(nums, target, m + 1, e, result);
}
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 42.9 MB, less than 99.29% of Java online submissions for Find First and Last Position of Element in Sorted Array.