leetcode 1365. 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

 

題目大意:給你一個數組nums,對於其中每個元素nums[i],請你統計數組中比它小的所有數字的數目.也就是說,對於每個nums[i]你必須計算出有效的j的數量,其中j滿足j != i 且 nums[j] < nums[i]. 以數組形式返回答案.

 

思路一:暴力法,對於每個nums[i], 統計數組中所有小於nums[i]的個數,時間復雜度$O(n^2)$.

C++代碼:

 1 class Solution {
 2 public:
 3     vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
 4         int len = nums.size();
 5         vector<int> cnt(len, 0);
 6         for (int index = 0; index < len; ++index) {
 7             for (int i = 0; i < len; ++i) {
 8                 if (i != index && nums[i] < nums[index])
 9                     cnt[index]++;
10             }
11         }
12         return cnt;
13     }
14 };

python3代碼:

 

思路二:由於數組中的數屬於[0,100], 可以利用計數排序的方式,先將數組排好序。

C++代碼:時間復雜度$O(n)$

class Solution {
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
        vector<int> cnt(101, 0);
        for (int i = 0; i < nums.size(); ++i) {//計數, cnt[i]此時統計的是數組中數i的個數
             cnt[nums[i]]++;
        }
        for (int i = 1; i < 101; ++i) {//cnt[i]統計的是數組中小於等於數i的個數
             cnt[i] += cnt[i - 1];
        }
        vector<int> ans(nums.size(), 0);
        for (int i = 0; i < nums.size(); ++i) {
            //如果nums[i] == 0, 說明數組中小於0的個數為0,否則小於nums[i]的個數為cnt[nums[i] - 1];
            ans[i] = (nums[i] == 0 ? 0 : cnt[nums[i] - 1]);
        }
        return ans;
    }
};

python3代碼:

時間復雜度O(nlogn)

class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        indics = {}
        for index, num in enumerate(sorted(nums)):
            indics.setdefault(num, index)
        return [indics[num] for num in nums]

時間復雜度O(n):

class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        count = collections.Counter(nums)

        for i in range(1,101):
            count[i] += count[i-1]
        
        return [count[x-1] for x in nums]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM