1. 程式人生 > 其它 >【LeetCode】315. Count of Smaller Numbers After Self 計算右側小於當前元素的個數(Medium)(JAVA)

【LeetCode】315. Count of Smaller Numbers After Self 計算右側小於當前元素的個數(Medium)(JAVA)

技術標籤:Leetcode演算法leetcode資料結構java排序

【LeetCode】315. Count of Smaller Numbers After Self 計算右側小於當前元素的個數(Medium)(JAVA)

題目地址: https://leetcode.com/problems/count-of-smaller-numbers-after-self/

題目描述:

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example 1:

Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Constraints:

  • 0 <= nums.length <= 10^5
  • -10^4<= nums[i] <= 10^4

題目大意

給定一個整數陣列 nums,按要求返回一個新陣列counts。陣列 counts 有該性質: counts[i] 的值是 nums[i] 右側小於nums[i] 的元素的數量。

提示:

  • 0 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

解題方法

  1. 這裡採用了插入排序,在插入前用二分法找出比當前元素小的個數
  2. 演算法複雜度 O(n^2),因為插入排序會移動位置
  3. note: 優化可以用歸併排序,歸併排序是唯一不改變穩定性(也就是逆序對個數),且時間複雜度為 O(nlogn) 的演算法
class Solution {
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> list = new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        for (int i = nums.length - 1; i >= 0; i--) {
            res.add(0, insert(list, nums[i]));
        }
        return res;
    }

    public int insert(List<Integer> list, int num) {
        if (list.size() == 0) {
            list.add(num);
            return 0;
        }
        int start = 0;
        int end = list.size() - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (list.get(mid) < num) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        list.add(start, num);
        return start;
    }
}

執行耗時:41 ms,擊敗了13.81% 的Java使用者
記憶體消耗:39.9 MB,擊敗了94.40% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新