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 != iandnums[j] < nums[i].
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).
If we sort the array, we can quickly determine how many numbers are smaller than each value by looking at the first index where it appears in the sorted array. This avoids nested loops and speeds up the process.
classSolution {
publicint[]smallerNumbersThanCurrent(int[] nums) {
int[] s = nums.clone();
Arrays.sort(s);
Map<Integer, Integer> m =new HashMap<>();
for (int i = 0; i < s.length; ++i) if (!m.containsKey(s[i])) m.put(s[i], i);
int[] ans =newint[nums.length];
for (int i = 0; i < nums.length; ++i) ans[i]= m.get(nums[i]);
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution {
funsmallerNumbersThanCurrent(nums: IntArray): IntArray {
val s = nums.sorted()
val m = mutableMapOf<Int, Int>()
for ((i, v) in s.withIndex()) if (v !in m) m[v] = i
return nums.map { m[it]!! }.toIntArray()
}
}
1
2
3
4
5
6
7
8
classSolution:
defsmallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:
s = sorted(nums)
m = {}
for i, v in enumerate(s):
if v notin m:
m[v] = i
return [m[x] for x in nums]
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnsmaller_numbers_than_current(nums: Vec<i32>) -> Vec<i32> {
letmut s = nums.clone();
s.sort();
letmut m = std::collections::HashMap::new();
for (i, &v) in s.iter().enumerate() {
m.entry(v).or_insert(i);
}
nums.iter().map(|&x|*m.get(&x).unwrap() asi32).collect()
}
}
1
2
3
4
5
6
7
8
classSolution {
smallerNumbersThanCurrent(nums: number[]):number[] {
consts= [...nums].sort((a, b) =>a-b);
constm: Record<number, number> = {};
for (leti=0; i<s.length; ++i) if (m[s[i]] ===undefined) m[s[i]] =i;
returnnums.map(x=>m[x]);
}
}