Address: https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/
<?php /** To give you an array nums, all figures for the number of each element nums [i], you count the array smaller than it therein. In other words, for each nums [i] You must calculate the effective number of j, where j satisfies j! = I and nums [j] <nums [i]. The answer is returned in an array. Example 1: Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Explanation: For nums [0] = 8, there are four smaller than its numbers: (1,2,2, and 3). For nums [1] = 1 is smaller than its number does not exist. There is a smaller number than it is for nums [2] = 2: (1). For nums [3] = 2 there is a smaller number than it: (1). For nums [4] = 3 it is smaller than the presence of three figures: (1 and 2). Example 2: Input: nums = [6,5,4,8] Output: [2,1,0,3] Example 3: Input: nums = [7,7,7,7] Output: [0,0,0,0] prompt: 2 <= nums.length <= 500 0 <= nums[i] <= 100 */ class Solution { /** 1. Create a new array, for him to sort into [8,3,2,2,1] 2. interchangeable key-value pair [ "8" => 0, "3" => 1, "2" => 3, "1" => 4] 3. Obtain the number less than the current value, because it is over the discharge sequence, so the subscript can represent numbers greater than he has several * ["8"=>5-1-0,"3"=>5-1-1,"2"=>5-1-3,"1"=>5-1-4] * ["8"=>4,"3"=>3,"2"=>1,"1"=>0] 4. convenient source array, filling values [4,0,1,1,3] */ function smallerNumbersThanCurrent1($nums) { $tmp_arr = $nums; rsort($tmp_arr); $tmp_arr = array_flip($tmp_arr); $length = count($nums); foreach ($tmp_arr as $key => $value) { $tmp_arr[$key] = $length - 1 -$tmp_arr[$key]; } $arr = []; foreach ($nums as $value) { $arr[] = $tmp_arr[$value]; } return $arr; } /** 1 Create an array, for him to sort into [1,2,2,3,8] 2 convenient source array, nest convenient new array, a new array index is equal to the number of in front of him as much as his array */ function smallerNumbersThanCurrent($nums) { $old_arr = $nums; $new_arr =[]; sort($old_arr); for($i =0;$i<count($nums);$i++){ foreach ($old_arr as $index=> $num){ if ($num == $nums[$i]) { array_push($new_arr,$index); break; } } } return $new_arr; } } $arr = [8,1,2,2,3]; $arr1 = [7,7,7,7]; $solution = new Solution(); var_dump($solution->smallerNumbersThanCurrent($arr));