40 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

分析

題意:對於數組中的每個數字,求出整個數組中比他小的數組的個數

最簡單的解法就是對於每個數字,都遍歷一遍數組挨個比較,這樣的話,複雜度顯然是n的n次方。
有沒有更好的解法?

很容易想到,將數組按升序排序,下標i,就是整個數組中比他小的數組的個數.
但是,對於重複的數據,下標i就不準確了。因此要對其去重。

解答

我寫了一個,報錯了。應該是遍歷出錯了,這個算法應該是雙層遍歷纔對,我只寫了一個。
排序去重的數組長度是MAX值101(nums[i] <= 100),nums的長度不確定,我不太清楚怎麼遍歷獲取。

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int len = nums.length;
        int[] res = new int[len];
        int[] afterSD = sortAndDist(nums);
        int i=0;
        int j=0;
        int k=0;
        while(k<len){
            if(afterSD[i]==0){
                i++;
                continue;
            }
            else if(afterSD[i]!=nums[j]){
                i++;
                j++;
                continue;
            }else {
                res[k]=i;
                k++;
            }
        }
        return res;
    }
    
    public int[] sortAndDist(int[] nums){
        int[] tmp = new int[101];
        for(int i=0;i<nums.length;i++){
            tmp[nums[i]]=1;
        }
        return tmp;
    }
}

看看別人寫的。
做法類似,但是思路不太一樣,
我想的算法還有個漏洞,比如[1,2,3,3,4],如果對其去重排序,得到的是
[1,2,3,4]
那麼比1小的有0個,比2小的有1個,比3小的有2個,到這裏都是正確的,
但是比4小的有3個,顯然是錯誤的。
因此去重還得記錄重複個數才行。

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int[] count = new int[101];
        int[] res = new int[nums.length];
        
        for (int i =0; i < nums.length; i++) {
        	// 這裏用的自增1的形式,count的數字表示對應下標的數據的重複個數
            count[nums[i]]++;
        }
        
        for (int i = 1 ; i <= 100; i++) {
        	// 把前一個數的個數,加到後一個上面,這樣,就統計了比當前數小的數據個數
        	// 比如count=[0,1,2,3],
        	// 意思是比0小的0個,
        	// 比1小的有1個
        	// 比i小的有count[i]個
        	// 累加之後count=[0,1,3,6],顯然是正確的。
            count[i] += count[i-1];    
        }
        
        for (int i = 0; i < nums.length; i++) {
	        // 如果是0,顯然比他小的只有0個
            if (nums[i] == 0)
                res[i] = 0;
            else  
                res[i] = count[nums[i] - 1];
        }
        
        return res;        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章