Leetcode Search for a Range (to find the starting and ending subscript for a given number in an ordered array)

Source: Internet
Author: User

title Link: https://leetcode.com/problems/search-for-a-range/?tab=Description Problem: Finds the start and end subscript of a given number in an array known as descending orderUse two times scanning; the first scan obtains the starting subscript for a given number (from subscript i==0 to Nums.lenght-1) The second pass scans the reference code starting with the subscript from the first scan:
 Packageleetcode_50;/*** *  * @authorPengfei_zheng * Find target starting and ending subscript in array*/ Public classSolution34 { Public Static int[] Searchrange (int[] Nums,inttarget) {                intStart = 0, end = nums.length-1; int[]ans = { -1,-1};  while(start<=end) {                intMid = (start + end)/2; if(Nums[mid] >=target) End= Mid-1; ElseStart= Mid + 1; if(nums[mid]==target) {ans[0]=mid; }} Start= Ans[0]==-1? 0:ans[0]; End=nums.length-1;  while(start<=end) {                intMid = (start+end)/2; if(nums[mid]<=target) Start= Mid + 1; ElseEnd= Mid-1; if(nums[mid]==target) ans[1]=mid; }        returnans; }     Public Static voidMain (String[]args) {int[]nums = {5, 7, 7, 8, 8, 10}; int[]ans = {0}; Ans= Searchrange (nums,8);  for(intItem:ans) {System.out.print (item+" "); }    }}

Leetcode Search for a Range (to find the starting and ending subscript for a given number in an ordered array)

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.