Search for a range to find the starting and ending positions of the specified element in an ordered sequence that may have repeating elements

Source: Internet
Author: User

Problem Description: Given an ordered sequence, the starting and ending positions of the specified element are found. Example: 1234555, 5, start 4 end 6

Algorithm analysis: In fact, is a two-point search for the use. But the special is not to find an element, but to find the subscript. That is, when Nums[mid]=target, the left and right elements of mid are analyzed.

 Public int[] Searchrange (int[] Nums,inttarget) {        if(Nums = =NULL|| Nums.length = = 0)        {            return NULL; }        int[] arr = { -1,-1}; BinarySearch (Nums,0, Nums.length-1, Target, arr); returnarr; }         Public voidBinarySearch (int[] Nums,intLeftintRightintTargetint[] arr) {        intMid = (left + right)/2; if(Left >Right ) {            return; }        if(Nums[left] = = Target && Nums[right] = = target)//Special Cases{arr[0] =Left ; arr[1] =Right ; return; }        if(Nums[mid] = =target) {            intTempl = Mid, Tempr =mid;  while(Templ>=left && nums[templ]==target) {Templ--; } arr[0] = templ+1;  while(Tempr<=right && nums[tempr]==target) {TEMPR++; } arr[1] = Tempr-1; }        Else if(Nums[mid] <target) {BinarySearch (nums, Mid+ 1, right, target, arr); }        Else{BinarySearch (Nums, left, mid-1, Target, arr); }    }

Search for a range to find the starting and ending positions of the specified element in an ordered sequence that may have repeating elements

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.