问题描述
Sort Array by Increasing Frequency
这是我完成的代码,但是在遵循可比结构时遇到一些问题,当两个整数的频率相同并且最大的整数将首先出现时,我无法遵循这种情况。
class Solution {
public int[] frequencySort(int[] nums) {
PriorityQueue<Pair> queue=new PriorityQueue<Pair>();
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{
if(map.containsKey(nums[i]))
{
map.put(nums[i],map.get(nums[i])+1);
}
else
{
map.put(nums[i],1);
}
}
for(int a:map.keySet())
{
queue.add(new Pair(a,map.get(a)));
}
int j=0;
while(!queue.isEmpty())
{
nums[j]=queue.peek().number;
queue.peek().frequency-=1;
if(queue.peek().frequency==0)
{
queue.poll();
}
j++;
}
return nums;
}
public class Pair implements Comparable<Pair>
{
int number;
int frequency;
public Pair(int number,int frequency)
{
this.number=number;
this.frequency=frequency;
}
public int compareto(Pair that)
{
if(this.frequency>that.frequency)
{
return 1;
}
return -1;
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)