题目描述
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
Given the array nums, for each nums[i] find out how many numbers in the array are
smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 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]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
博主提交的代码
解法一 简单直接,时间复杂度O(n^2),空间复杂度O(1)
这个正常人直观都能想到的解法
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] result = new int[nums.length];
for(int i = 0; i < nums.length; i++){
for(int eachInnerInt: nums){
if( nums[i] > eachInnerInt){
result[i]++;
}
}
}
return result;
}
解法二,先排序再输出,时间复杂度依赖于你的排序算法
我们采用jdk默认的排序算法来进行排序
public int[] smallerNumbersThanCurrent(int[] nums) {
// 需要clone的原因是Arrays.sort会改变入参的顺序
int[] backup = nums.clone();
// Jdk 1.8的Arrays.sort的官方javadoc中已经写明此方法原理和时间复杂度,为nlogn
Arrays.sort(backup);
Map<Integer,Integer> dataIndex = new HashMap<>();
int ordinal = 0;
for(int sortedInt: backup){
if( dataIndex.get(sortedInt) == null){
dataIndex.put(sortedInt,ordinal);
}
ordinal++;
}
int[] result = new int[nums.length];
for(int i = 0;i < nums.length; i++){
result[i] = dataIndex.get(nums[i]);
}
return result;
}
他人优秀的代码
解法一
这个解法是nums里面的值比较大的时候,并不太适用,但是在这道题的背景下还是可以的
public int[] smallerNumbersThanCurrent(int[] nums) {
int n = nums.length;
int[] c1 = new int[101]; // 0 <= nums[i] <= 100
for (int i : nums) {
c1[i]++;
}
int[] c2 = new int[101];
c2[0] = c1[0];
for (int i = 1; i < 101; i++) {
c2[i] = c1[i] + c2[i - 1];
}
int[] ans = new int[n];
int idx = 0;
for (int i : nums) {
ans[idx++] = c2[i] - c1[i];
}
return ans;
}