Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
035. Search for a Range (Medium)
links:
Title: https://leetcode.com/problems/search-for-a-range/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Finds a range of numbers in an ordered array. (because the number is duplicated)
Analysis:
Or two-point search variants.
- (c + +) directly with C + + STL
lower_bound
and upper_bound
lazy.
- (Java) just change it directly from the ordinary two points.
Code:
C++:
Class solution {public:vector<int> Searchrange (int a[], int n, int target) {int* lower = Lower_bound (A, a + N, targe t); int* upper = Upper_bound (A, a + N, target); if (*lower! = target) return vector<int> {-1, -1};elsereturn vector< Int>{lower-a, upper-a-1};};
Java:
public class Solution {public int[] Searchrange (int[] A, int target) { int[] ret = new int[2]; Ret[0] = ret[1] =-1; int left = 0, right = a.length-1, mid; while (left <= right) { if (a[left] = = Target && A[right] = = target) { ret[0] = left; RET[1] = right; break; } Mid = (right + left)/2; if (A[mid] < target) {left = mid + 1, } else if (A[mid] > target) {right = mid-1; } else {
if (a[right] = = target) { ++left; } else { --right;}} } return ret; }}
[Leetcode] 034. Search for a Range (Medium) (C++/java)