"Leetcode" Search for a Range

Source: Internet
Author: User

Problem description

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].
Find a range of occurrences of a number in a sorted array

Algorithmic thinking

Two-point lookup to the number of targets before and after order lookup

Algorithm implementation
 Public classSolution { Public int[]Searchrange(int[] Nums,intTarget) {int[] result =New int[] { -1, -1};if(Nums = =NULL|| Nums.length = =0)returnResultintloc = Arrays.binarysearch (nums, target);if(Loc <0)returnResultElse{inti = loc, j = loc; while(i>=0&&nums[i] = = target) {i--;} while(J<nums.length&&nums[j] = = target)            {j + +;} result[0] = i+1; result[1] = J1; }returnResult }}
Algorithm time

Algorithm time is two minutes to find time
T (n) =o (LOGN)
But if all the numbers are the same, the lookup time is O (1), the sequential lookup time is O (n), so the worst case is O (n)

Demo results
 Public Static void Main(string[] args) {intResult[] =New int[] { -1, -1};int[] arr = {1, at, the, the, the, the, the, Wu, $, the}; result = Searchrange (arr, $); System. out. println (result[0] +":"+ result[1]); }

8:8

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Leetcode" Search for a Range

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.