[Lintcode 14] First Position of Target

Source: Internet
Author: User
Tags lintcode


For a given sorted array (ascending order) and a number target , find the first index of this number in time O(log n) complexit Y.

If the target number does not exist in the array, return -1 .

Example

If the array is [1, 2, 3, 3, 4, 5, 10] , for given target 3 , return 2 .

Analysis: An ordered array is given in the question, and each element is not necessarily unique, finding the position where the target first appears. The key to this problem is that when nums[mid] = = target, instead of returning mid, it moves the mid point of the end and continues looking forward to see if there are no identical elements.

classSolution {/**     * @paramnums:the an integer array. * @paramTarget:target to find. * @return: The first position of target.     Position starts from 0. */     Public intBinarySearch (int[] Nums,inttarget) {        if(Nums.length = = 0) {            return-1; }        intStart = 0, end = nums.length-1;  while(Start + 1 <end) {            intMID = start + (End-start)/2; if(Nums[mid] = =target) {End=mid; }Else if(Nums[mid] <target) {Start=mid; }Else{End=mid; }        }        if(Nums[start] = =target) {            returnstart; }        if(Nums[end] = =target) {            returnend; }        return-1; }}

[Lintcode 14] First Position of Target

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.