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:

    1. Input: nums = [8,1,2,2,3]
    2. Output: [4,0,1,1,3]
    3. Explanation:
    4. For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
    5. For nums[1]=1 does not exist any smaller number than it.
    6. For nums[2]=2 there exist one smaller number than it (1).
    7. For nums[3]=2 there exist one smaller number than it (1).
    8. For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

    Example 2:

    1. Input: nums = [6,5,4,8]
    2. Output: [2,1,0,3]

    Example 3:

    1. Input: nums = [7,7,7,7]
    2. Output: [0,0,0,0]

    Constraints:

    • 2 <= nums.length <= 500
    • 0 <= nums[i] <= 100

    题意

    对于一个数组nums中的每一个数nums[i],统计小于nums[i]的数的个数。

    思路

    1. 暴力法。


    代码实现 - 暴力法

    1. class Solution {
    2. public int[] smallerNumbersThanCurrent(int[] nums) {
    3. int[] ans = new int[nums.length];
    4. for (int i = 0; i < nums.length; i++) {
    5. for (int j = 0; j < nums.length; j++) {
    6. if (j != i && nums[j] < nums[i]) {
    7. ans[i]++;
    8. }
    9. }
    10. }
    11. return ans;
    12. }
    13. }

    代码实现 - Hash

    1. class Solution {
    2. public int[] smallerNumbersThanCurrent(int[] nums) {
    3. int[] ans = new int[nums.length];
    4. Map<Integer, Integer> hash = new TreeMap<>();
    5. for (int i = 0; i < nums.length; i++) {
    6. if (!hash.containsKey(nums[i])) {
    7. hash.put(nums[i], 1);
    8. } else {
    9. hash.put(nums[i], hash.get(nums[i]) + 1);
    10. }
    11. }
    12. int sum = 0;
    13. for (int key : hash.keySet()) {
    14. int temp = sum + hash.get(key);
    15. hash.put(key, sum);
    16. sum = temp;
    17. }
    18. for (int i = 0; i < ans.length; i++) {
    19. ans[i] = hash.get(nums[i]);
    20. }
    21. return ans;
    22. }
    23. }

    代码实现 - 二分法

    1. class Solution {
    2. public int[] smallerNumbersThanCurrent(int[] nums) {
    3. int[] ans = new int[nums.length];
    4. int[] copy = Arrays.copyOf(nums, nums.length);
    5. Arrays.sort(copy);
    6. for (int i = 0; i < ans.length; i++) {
    7. ans[i] = binarySearch(copy, nums[i]);
    8. }
    9. return ans;
    10. }
    11. private int binarySearch(int[] nums, int target) {
    12. int left = 0, right = nums.length - 1;
    13. while (left < right) {
    14. int mid = left + (right - left) / 2;
    15. if (nums[mid] < target) {
    16. left = mid + 1;
    17. } else if (nums[mid] >= target) {
    18. right = mid;
    19. }
    20. }
    21. return left;
    22. }
    23. }