问题链接: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]
.
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.youkuaiyun.com/jmspan/article/details/51219203还是看得不大明白,等把数据结构看完再来分析下,看能不能彻底明白。