java将整数数组按频率降序排序
我需要从jTextFrame中提取一个字符串,然后按出现的顺序排序,然后打印出来。babablackbike return:bbbbaakceil
String word = (String)jTextField1.getText();
String indexes = "abcdefghijklmnopqrstuvwxyz";
int[] count = new int[indexes.length()];
for (int i = 0; i < word.length(); i++)
{
int index = indexes.indexOf(word.charAt(i));
if (index < 0)
continue;
count[index]++;
}
for (int j = 0; j < count.length; j++)
{
if (count[j] < 1)
continue;
char[] indiv = indexes.toCharArray();
for (int p = 0; p < count[j];p++)
{
jTextArea1.append(""+indiv[j]);
System.out.println(indiv[(j)] +"="+ count[j] + p);
}
}
# 1 楼答案
首先需要获得输入中每个字符的计数:
由于Java在
char[]
与Character[]
之间有点特殊——由于泛型不能处理原语,因此无法使用自定义比较器对原语进行排序——我同时也构建了一个List<Character>
现在我们只需要使用自定义
Comparator
和Map counts
中的信息对List<Character>
进行排序:因此,首先我们按照输入中字符的计数进行排序(逆序),然后我们按照字符本身进行排序
现在我们只需要将
List
构建回String
:输出:
# 2 楼答案
我认为,最好的解决方案是创建这样的HashMap
然后,你可以这样做一个循环:
之后,您可以按值对其进行排序并轻松打印
# 3 楼答案
以下是一般算法:
下面是一个编码示例: