Hi All, This is the first time I am posting on the Leetcode discuss section related to one minor problem I am facing on one of the Leetcode Hard problems so if I am posting this in the wrong place for my problem to be solved, let me know I will delete it and post at the right section.
So from last weeks I just started solving @Leetcode Hard problems, and I am really enjoying it. But I need some expert help now regarding one famous leetcode hard problem.
Problem URL: https://leetcode.com/problems/count-of-smaller-numbers-after-self/
315. Count of Smaller Numbers After Self
Before seeing the best approach for this problem in discuss section, i just tried to solve this problem using some different method or totally different way compare to all Accepted Solution.
And Luckily my solution is passing 63/65 test cases
So two-trick which I have used here is the reversal approach & Hashmap to get the count if and only if already visited and both are consecutive and adding it to the front of the list using the list.add(0, count[i]).
class Solution {
public List<Integer> countSmaller(int[] nums) {
HashMap<Integer,Integer> map=new HashMap<>();
List<Integer> list=new ArrayList<>();
if(nums.length==0 || nums==null)
return list;
int[] count=new int[nums.length];
for(int i=nums.length-1;i>=0;i--){
if(map.containsKey(nums[i]) && nums[i+1]==nums[i]){
list.add(0,map.get(nums[i]));
continue;
}
for(int j=i+1;j<=nums.length-1;j++){
if(nums[i]>nums[j])
count[i]++;
}
map.put(nums[i],count[i]);
list.add(0,count[i]);
}
return list;
}
}