回复 2楼 peach5460
如果百度上能解决的,我就不会拿这上面来丢人了。
int element_count(const std::vector<int> &set, int e) { int left, right, middle; left = 0, right = set.size() - 1; int count = 0; while (left <= right) { middle = (left + right) / 2; if (set.at(middle) > e) { right = middle - 1; } else if (set.at(middle) < e) { left = middle + 1; } else { while (middle - 1 >= 0 && set.at(middle) == set.at(middle - 1)) middle -= 1; while (set.at(middle) == set.at(middle + 1)) { middle += 1; ++count; } return ++count; } } return 0; }
int element_count(int * set, int len, int e) { int min=0,max=len-1,mid,count=0,k; while(min < max) { mid=(min+max)/2; if(set[mid]==x) { count = 1; for(k = mid ; k >= 0 && set[k]==x ; k --); count += (mid-k); for(k = mid ; k < len && set[k]==x ; k ++); count += (k-mid); break; } else if(set[mid]>x) right=mid-1; else left=mid+1; } return count; }