given an ascending array of integers nums, and a target value target. Find the starting and ending positions in the array for the given target value.
your algorithm’s time complexity must be O(log n).
if there is no target value in the array, return [-1, -1].
example 1 strong> : p>
enter strong> : nums =,7,7,8,8,10 [5], target = 8
strong> output: [3, 4] p>
sample 2 strong> : p>
enter strong> : nums =,7,7,8,8,10 [5], target = 6
strong> output: [1, 1] p>
thought and code
O(log n) is the complexity of
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[] {-1, -1};
if (nums.length < 1) return res;
int firstIndex = search(nums, target - 1);
// 如果大于target-1 的第一个索引就超级界 或者 第一个索引的值不是target 那么就说明当前数组没有目标值
if (firstIndex == nums.length || nums[firstIndex] != target) return res;
else res[0] = firstIndex;
res[1] = search(nums, target) - 1;
return res;
}
public int search(int[] nums, int target) {
// 找到大于target值的第一个位置
int l = 0, r = nums.length;
while (l < r) {
int m = l + (r - l) / 2;
if (target >= nums[m]) l = m + 1;
else r = m;
}
return l;
}
}
div>
Read More:
- LeetCode 23. Merge k Sorted Lists(java)
- Leetcode solution 189 Rotate Array Java version
- Array of PHP_ diff,array_ intersect,array_ merge, in_ Is there a limit on the number of arrays in array?
- array type has an incomplete element type
- After JQ gets the tag element itself, it gets its own HTML text format (find only finds one level of child elements)
- Grep finds all files containing a string in Linux
- An error is displayed when virtualbox uses modifyhd command to expand capacity: Resize medium operation for this format is not implemented yet
- error C2057: expected constant expression (Can the size of an array in C language be defined when the program is running?)
- If JavaScript exceeds the length of the array, no error will be reported
- [solved] error: valueerror: expected 2D array, got scalar array instead
- Error tips:array type has incomplete element type
- The sum of the two numbers of leetcode
- 21. Merge Two Sorted Lists [easy] (Python)
- The echots in Vue reports an error. After obtaining the DOM element, the chart can be displayed. The console still reports an error
- Selenium reports an error and solves the problem of element not interactive exception, element not interactive
- JavaScript removes the number specified in the array
- python MemoryError: Unable to allocate 165. MiB for an array with shape
- Remove array duplicate elements
- numpy.logspace () produces an array
- Node.js Medium package.json The difference between devdependences and dependencies