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;        
    }
}
发布了118 篇原创文章 · 获赞 26 · 访问量 8007

猜你喜欢

转载自blog.csdn.net/weixin_43367550/article/details/104653438