C + +-two points find the full version (including attention to detail)

Source: Internet
Author: User

  int getpos (Vector<int> a, int n, int val)               int left = 0;int right =  n-1;    int index = n; while (left <= right) {int  mid =  (left+right)/2;if (a[mid] == val)          {            if (Mid < index)    index = mid;             right = mid -1;        }else if (A[mid]  > val) right = mid-1;else if (A[mid] < val) left = mid+1;}         if (index != n)          return index; &nbsP;  else        return -1; // write code  here    }

As shown in the code above, the binary lookup is mainly to control the progressive relationship between the left and right two pointers. The first consideration is that the while loop must be left<=rigtht, not left<right, or the first number cannot be processed to find the number. Second, when you find it, you have to decide if you have the same keyword in front of you to make sure the number you are looking for is the first occurrence.

This article is from the "11292692" blog, please be sure to keep this source http://11302692.blog.51cto.com/11292692/1826850

C + +-two points find the full version (including attention to detail)

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.