概要
題目來源鏈接:https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/
難度:簡單
類型:數組
題目
給你一個數組 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)。
示例 2:
輸入:nums = [6,5,4,8]
輸出:[2,1,0,3]
示例 3:
輸入:nums = [7,7,7,7]
輸出:[0,0,0,0]
提示:
2 <= nums.length <= 500
0 <= nums[i] <= 100
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析
作者下面的代碼使用的是暴力破解,即循環遍歷數組,將整個數組的元素依次與其比較,如果比當前元素小,則計數器加1。
關於更多的思路參考LeetCode上的題解https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/solution/
代碼
Java代碼
/**
* 有多少小於當前數字的數字
*
* @param nums 要求統計的數組
* @return 返回數組中比它小的所有數字的數目
*/
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] results = new int[nums.length];// 創建一個結果數組
for (int i = 0; i < nums.length; i++) {// 循環遍歷一維數組的元素
int count = 0;// 計數器,記錄當前元素比它小的所有數字的數目,初始值爲0
for (int j = 0; j < nums.length; j++) {// 循環遍歷所有元素
if (nums[i] > nums[j]) {// 將當前元素與數組中的所有元素比較
count++;// 如果當前元素比被比較的元素大,則計數器加1
}
}
results[i] = count;// 將當前元素的計數器結果保存到result數組中
}
return results;
}