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)