Title: Found, "Super Water King" no more. System-knot-fruit Table-ming, there are 3 posts a lot of IDs, their number is more than the total number of N of 1/4. Can you quickly find their ID from the list of IDs?
Ideas: Associative containers can be easily solved, PHP is an array of associative arrays, PHP has a lot of convenient sorting functions, so this time with PHP implementation.
First, the ID list is traversed, and the ID is the key value of the array $result to assign the value,
If $result[$id] is not initialized, then this is the first occurrence, that is $result[$id]=1
If $result[$id] has been initialized, the number of posts added is 1, which is $result[$id]++
The value of the last $result array is sorted in descending order, and the first three elements taken out are three Aqua kings.
Start with the sort, did not notice the key name changed, and then read the manual:
Note: This function array assigns the new key name to the element in. This will delete the original key name instead of just reordering the key name.
Here's a look at the sort functions of PHP:
The sort () function is used to sort the array cells from low to high.
The Rsort () function is used to sort the array cells from high to low.
The Asort () function is used to sort the array cells from low to high and keep the index relationship.
The Arsort () function is used to sort the array cells from high to low and keep the index relationship.
The Ksort () function is used to sort the array cells from low to high by their key names.
The Krsort () function is used to sort the array cells by their key names from high to low.
1<?PHP2 $idlist=Array(1,1,2,2,3,3,4);//ID List3 4 functionValidate$list)5 {6 $result=Array();7 foreach($list as $v)8 {9 if(!isset($result[$v]))//first occurrence, assigning the initial number of posts to 1Ten { One $result[$v] = 1; A}Else //appear again, posts number +1 - { - $result[$v]++; the } - } - if(Arsort($result))//Sort each ID in descending order by number of posts - { + Reset($result); - Next($result); + Next($result); A if( Current($result) < (Count($list)/4))//confirm that the number of posts for the Three Kings is greater than the total number of posts at { - die(' ID list is illegal! ‘); - } - } - Reset($result); - Echo Key($result) . ' <br > '; in Next($result); - Echo Key($result) . ' <br > '; to Next($result); + Echo Key($result) . ' <br > '; - } the *Validate$idlist); $ Panax Notoginseng?>
The time complexity is O (n) when inserting a new key for the first time
Time complexity of Lookup is O (1)
Sort with a quick row O (NLOGN) ~ (n^s) 1<s<2
Time should be slower.
Software Engineering class practice find water King s