题目描述


给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。
换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。
以数组形式返回答案。


  • 解题思路

    题干给的提示感觉挺多了,使用一个count来记录nums中每一个数据与另外数据比较后的结果,然后把count加到一个新的数组arr当中,题干要求以数组的形式返回,所以就返回这个arr数组就行了,如果没有比数组中其他元素大的(也就是最小的元素)也需要计数,记为0,所以arr数组长度就是nums数组的长度。
  • 解答

    class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        //定义一个新数组,存结果
        int[] arr = new int[nums.length]; 
        //k用来做数组的游标,count用来记录每一轮比较后的结果
        int k = 0;
        int count = 0;
        //使用一个双循环,
        for(int i = 0;i < nums.length ;i++){
            for(int j = 0;j < nums.length;j++){
                if(j == i){//自己不能比自己,跳过
                    continue;
                }
                if(nums[j] < nums[i]){//如果小于自己,计数加1
                    count++;
                }
            }
            //把这次的结果存到数组中
            arr[k] = count;
            //游标移动一个位置
            k++;
            //把计数归零
            count = 0;
        }
        return arr;
    }
}