315. Count of Smaller Numbers After Self

问题链接:https://leetcode.com/problems/count-of-smaller-numbers-after-self/?tab=Description

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:

Given nums = [5, 2, 6, 1]

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.

Return the array [2, 1, 1, 0].

拿到题目,第一思路是:采用DP算法从后向前,建立一个数组value[nums.length],最后一个元素的值为0,依次向前,value[i]的值为从i+1到length-1的nums数组中的max{小于value[i]}的下标k对应的value[k]+1,这样实现最简单,但是时间复杂度为n^2,空间复杂度为线性。

public class Solution {
    int[] value;
    
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if(nums==null || nums.length==0)
            return res;
        int len = nums.length;
        value = new int[len];
        value[len-1] = 0;
        if(len==1) {
            res.add(0);
            return res;
        }
        for(int index=len-2;index>=0;index--) {
            int first = theFirstSmallNum(nums, index, len);
            if(first==-1) {
                value[index] = 0;
            } else {
                value[index] = value[first] + 1;
            }
        }
        for(int i=0;i<len;i++) {
            res.add(value[i]);
        }
        return res;
    }
    
    private int theFirstSmallNum(int[] nums, int begin, int right) {
        int smallMax = begin+1;
        for(int i=begin+1;i<right;i++) {
            if(nums[i] < nums[begin]) {
                smallMax = nums[smallMax]>nums[i]?smallMax:i;
            }
        }
        return smallMax==begin+1? -1 : smallMax;
    }
}
或者更直接的方式:

public class Solution {
    
    public List<Integer> countSmaller(int[] nums) {
        if(nums==null || nums.length==0) return new ArrayList<Integer>();
        
        int len = nums.length;
        int[] value = new int[len];
        
        for(int i=0;i<=len-1;i++) {
            for(int j=i+1;j<=len-1;j++) {
                if(nums[i]>nums[j])
                    value[i]++;
            }
        }
        
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<len;i++) {
            list.add(value[i]);
        }
        
        return list;
    }
}
但是,Time Limit Exceeded,果然最简单的方式肯定是最大代价,不能通过的。

先做下记录,参照答案http://blog.csdn.net/jmspan/article/details/51219203还是看得不大明白,等把数据结构看完再来分析下,看能不能彻底明白。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值