简体   繁体   中英

Finding a better than Brute Force algorithm

The problem is as follows: Given a stream of data with names of people, their height and their weight, for each employee E, find the group of employees that are taller and weigh more than E.

Obviously, this can be brute forced in O(n^2). Is this the best you can do though? If it's possible to do better, what would be the algorithm ?

If we draw a point (height_i, weight_i) on a 2D plane for every employee i , the query of employee i becomes 2D orthogonal range query, ie finding points within this rectangle height_i < height <= height_max and weight_i < weight <= weight_max .

From wiki[1], you can have an algorithm with time complexity O(n log log n + k) where k is the size of output.

Edit: In worst case, k can be in order of n^2

1: https://en.wikipedia.org/wiki/Range_searching#Orthogonal_range_searching

If you sort the input on either height or weight, you can go through checking only the subsequent entries for each entry, so you can do (l-1) + (l-2) + (l-3) + ... + 1 comparisons instead of l * (l - 1) . Obviously this is still quadratic, though. As ruakh pointed out in their comment, the output size tells us that this is the best we can do (imagine the case where every person in the sorted list is shorter and weighs less than every subsequent person).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM