Leetcode Two-point search search for a Range

Source: Internet
Author: User

Search for a Range Total accepted:21480 Total submissions:78454 My Submissions

Given a sorted array of integers, find the starting and ending position of a Given target value.

Your algorithm ' s runtime complexity must is in the order of O (log n).

If the target is not a found in the array, return [-1,-1].

For example,
Given [5, 7, 7, 8, 8, ten] and target value 8,
return [3, 4].
Test instructions: In a well-ordered array, look for the starting subscript and end subscript for a given value
Idea: two-point search
First use Lower_bound to find the starting subscript
and use Upper_bound to find the end subscript.
Lower_bound and Upper_bound Implementation see STL Source code Analysis
Complexity: Time O (log n) space O (1)

vector<int> searchrange (int a[], int n, int target) {
	int l = distance (A, lower_bound (a, a + N, target));
	int u = Distance (A, upper_bound (a, a + N, target));
	vector<int> Res;
	if (a[l]! = target) {
		res.push_back ( -1);
		Res.push_back ( -1);
	} else{
		Res.push_back (l);
		Res.push_back (u-1);
	}
	return res;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.