給你一個數組 nums,對于其中每個元素 nums[i],請你統計數組中比它小的所有數字的數目。
換而言之,對于每個 nums[i] 你必須計算出有效的 j 的數量,其中 j 滿足 j != i 且 nums[j] < nums[i] 。
以數組形式返回答案。
示例 1:
輸入:nums = [8,1,2,2,3]
輸出:[4,0,1,1,3]
解釋:
對于 nums[0]=8 存在四個比它小的數字:(1,2,2 和 3)。
對于 nums[1]=1 不存在比它小的數字。
對于 nums[2]=2 存在一個比它小的數字:(1)。
對于 nums[3]=2 存在一個比它小的數字:(1)。
對于 nums[4]=3 存在三個比它小的數字:(1,2 和 2)。
代碼
class Solution {public int[] smallerNumbersThanCurrent(int[] nums) {int[] res=new int[nums.length];int[][] loc=new int[nums.length][2];for(int i=0;i<nums.length;i++)//構造二維數組記錄排序前數組的下標{loc[i][0]=nums[i];loc[i][1]=i;}Arrays.sort(loc,((o1, o2) -> o1[0]-o2[0]));//按大小排序res[loc[0][1]]=0;for(int i=1;i<nums.length;i++){if(loc[i][0]==loc[i-1][0])//兩個元素大小相等,結果也是一樣的res[loc[i][1]]=res[loc[i-1][1]];else res[loc[i][1]]=i;//排序后的元素下標就是小于該元素的數字個數}return res;}
}