gpt4 book ai didi

java - 根据出现次数升序排列数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:31:13 25 4
gpt4 key购买 nike

如何在 java 中根据该值的出现次数按升序排列数组中的元素。

这是我试过的:

int a[]={0,0,0,1,3,3,2,1,3,5,6,0};
int b=a.length;
for(int i=0;i<b;i++) {
for(int j=0;j<i;j++) {
int temp;
if( a[j]>a[i]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

for(int r=0;r<a.length;r++) {
System.out.println(a[r]);
}

最佳答案

这是使用 TreeMap 进行此操作的有效方法。

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class FrequencySort {
public static void main(String[] args) {
int[] ar = new int[] {5,2,8,8,5,5,8,1,9,0,1,1,0,1};

Map<Integer,Integer> numbers = new HashMap<>();

for(int number : ar) {
if(numbers.containsKey(number)) {
Integer count = numbers.get(number);
numbers.put(number, ++count);
} else {
numbers.put(number,1);
}
}

final class FrequencyComparator implements Comparator<Integer> {
Map<Integer,Integer> refMap;
public FrequencyComparator(Map<Integer,Integer> base) {
this.refMap = base;
}

@Override
public int compare(Integer k1, Integer k2) {
Integer val1 = refMap.get(k1);
Integer val2 = refMap.get(k2);

int num = val1.compareTo(val2) ;
// if frequencies are same then compare number itself
return num == 0 ? k1.compareTo(k2) : num;
}
}

FrequencyComparator comp = new FrequencyComparator(numbers);
TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(comp);
sortedMap.putAll(numbers);
for(Integer i : sortedMap.keySet()) {
int frequencey = sortedMap.get(i);
for(int count = 1 ; count <= frequencey ; count++) {
System.out.print(i + " " );
}
}
}
}

关于java - 根据出现次数升序排列数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11842984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com