1. Problem definition:
In an ordered array, search for all elements in the input array that meet the conditions of a value greater than a value and a value less than B. Where a and B may not be in the array.
2. Example description:
Input array eg: {, 33, 45, 49 }. If all the numbers greater than 10 and less than 30 are found, the output result is a subset of {11, 16, 31. If the query value is greater than 50 or less than 2, the output empty set is displayed.
3. linear scanning:
Complexity O (n) scanning from left to right to meet the condition range
4. Binary Search:
Complexity O (logn) binary search meets the condition range, two binary searches, determine the subarray range.
auto binary_search_left(const vector<int>& nums,int min,int max){ if(nums.empty()) return -1; int left=0; int right =nums.size()-1; auto min_left=-1; while(left<=right) { auto mid=(left+right)/2; if(nums[mid]<min){ left=mid+1; continue; } if(nums[mid]>max){ right=mid-1; continue; } min_left=mid; right=mid-1; } return min_left;}auto binary_search_right(const vector<int>& nums,int min,int max){ if(nums.empty()) return -1; int left=0; int right =nums.size()-1; auto max_right=-1; while(left<=right) { auto mid=(left+right)/2; if(nums[mid]<min){ left=mid+1;//mid+1 continue; } if(nums[mid]>max){ right=mid-1; continue; } max_right=mid; left=mid+1; } return max_right;}
5. Where can I apply it?
For example, the tower anti-DDoS game has a lot of bullet detection, and the dual for loop traverses all bullets and monsters will have a lot of redundant detection graphics intersection calculation. So what should we do? Our space division technology sorts bullets or monsters by X axis coordinates. Only bullets or monsters within a certain range need collision detection (Graphic intersection calculation ). Fast sorting is adopted. The time complexity O (nlogn) is located in a sorted array to find the intervals that meet the conditions. The time complexity is O (logn) by means of binary search ). Although sorting and search operations are introduced, the cost model of sorting and search is only a comparison operation and a value assignment operation. What's better is that we greatly reduce collision detection (Graphic intersection calculation ).