Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shivani13121007/788529b9122f807948890a808441c7ff to your computer and use it in GitHub Desktop.
Save Shivani13121007/788529b9122f807948890a808441c7ff to your computer and use it in GitHub Desktop.
How Many Numbers Are Smaller Than the Current Number
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] ans = new int[nums.length];
// Brute Technique
// for(int i=0;i<nums.length;i++)
// {
// int c=0;
// for(int j=0;j<nums.length;j++)
// {
// if(nums[i]>=nums[j] && nums[i] != nums[j])
// {
// c++;
// }
// }
// ans[i] = c;
// }
// Another Approach
int[] helper = new int[nums.length];
for(int i=0;i<nums.length;i++)
{
helper[i] = nums[i];
}
// for(int i=0;i<helper.length;i++)
// {
// for(int j=i+1;j<helper.length;j++)
// {
// if(helper[i]>=helper[j])
// {
// int t = helper[i];
// helper[i] = helper[j];
// helper[j] = helper[i];
// }
// }
// }
Arrays.sort(helper);
HashMap<Integer,Integer> hm = new HashMap<>();
hm.put(helper[0],0);
for(int i=1;i<helper.length;i++)
{
if(helper[i] == helper[i-1])
{
hm.put(helper[i],hm.get(helper[i-1]));
}
else{
hm.put(helper[i],i);
}
}
for(int i=0;i<nums.length;i++)
{
if(hm.containsKey(nums[i]))
ans[i] = hm.get(nums[i]);
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment