如何根据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]);
}
答案 0 :(得分:7)
这是使用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 + " " );
}
}
}
}
答案 1 :(得分:4)
启动你的一种方法可能是基于保持计算初始数组中每个整数在地图中出现的次数的想法。计算完所有数字后,按升序排序地图,然后打印地图输出:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;
public class SortCount {
public static void main(String[] args) {
int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++) {
if(counts.containsKey(nums[
Integer c = counts.get(nums[i]) + 1;
counts.put(nums[i], c);
}
else {
counts.put(nums[i],1);
}
}
ValueComparator<Integer,Integer> bvc = new ValueComparator<Integer,Integer>(counts);
TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(bvc);
sortedMap.putAll(counts);
ArrayList<Integer> output = new ArrayList<Integer>();
for(Integer i : sortedMap.keySet()) {
for(int c = 0; c < sortedMap.get(i); c++) {
output.add(i);
}
}
System.out.println(output.toString());
}
}
使用Comparator
类来比较Map
中的值:
import java.util.Comparator;
import java.util.Map;
public class ValueComparator<T1,T2 extends Comparable<T2>> implements Comparator<T1> {
Map<T1,T2> base;
public ValueComparator(Map<T1,T2> base) {
this.base = base;
}
@Override
public int compare(T1 k1, T1 k2) {
T2 val1 = base.get(k1);
T2 val2 = base.get(k2);
return val1.compareTo(val2);
}
}
答案 2 :(得分:3)
如果您只想sort数组,请使用以下命令:
Arrays.sort(a);
如果您想手动对其进行排序,我建议您阅读this页面,您可以在其中找到各种排序算法的伪代码。
但是,如果您正在搜索基于数字频率对数组进行排序的方法,我建议您this页面。您必须按顺序反转排序顺序,希望它们按升序排列。
答案 3 :(得分:2)
Arrays.sort(int[])
怎么样?来自它的JavaDoc:
将指定数组按数字升序排序。
答案 4 :(得分:1)
public static void main(String[] args) {
int unsortedArray[] = {0,0,0,1,3,3,2,1,3,5,6,0};
System.out.println("After sorting, the list elements are: "); //Just to show you it worked. :)
bubbleSoprt(unsortedArray,unsortedArray.length);
for(int i =0;i<unsortedArray.length;i++){
System.out.print( unsortedArray[i] + " ");
}
}
private static void bubbleSoprt(int []unsortedarray,int lenght){
int temp;
for(int counter= 0 ;counter<lenght-1;counter++){
for(int index = 0;index<lenght-1-counter;index++){
if(unsortedarray[index] > unsortedarray[index+1]){
temp = unsortedarray[index];
unsortedarray[index] = unsortedarray[index+1];
unsortedarray[index+1] = temp;
}
}
}
}
答案 5 :(得分:1)
尝试:
int a[] = {0,0,0,1,3,3,2,1,3,5,6,0};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
答案 6 :(得分:1)
轻松优化。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Frequency {
public static void main(String[] args) {
int array[] = {5,2,8,8,5,5,8,1,1,2};
HashMap<Integer, Integer> data = new HashMap<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
if (data.containsKey(array[i])) {
Integer count = data.get(array[i]) + 1;
data.put(array[i], count);
} else {
data.put(array[i], 1);
}
}
Set<Entry<Integer, Integer>> set = data.entrySet();
ArrayList<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
for (Entry<Integer, Integer> entry : list) {
System.out.println(entry.getKey() + " <-> " + entry.getValue());
}
}
}
答案 7 :(得分:1)
使用TreeMap将元素存储为键,将出现次数存储为值,然后根据值对它进行排序。 Java 8流使以下代码简洁明了
int[] a = {1,1,2,2,3,3,3,4,4,5,5,5,5,6,6,6,8};
// new element ? store its count as 1 , else increment its count
TreeMap<Integer,Integer> m1 = new TreeMap<>();
for(int i : a)
{
if(m1.containsKey(i))
{m1.put(i,m1.get(i)+1);}
else {m1.put(i,1);}
};
// sort and then if element i occurs n times, simply loop to add so in arraylist
ArrayList<Integer> b = new ArrayList<>();
m1.entrySet().stream()
.sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue())).forEach(e -> {
for(int i=0;i<e.getValue();i++)
b.add(e.getKey());
});
Arrays.stream(a).forEach(i -> System.out.print(i+ " "));
System.out.println();
b.stream().forEach(i -> System.out.print(i+ " "));
}
答案 8 :(得分:0)
从Java 8开始,您可以使用单行代码(分成几行以获得更好的可读性;-)来实现此目的
int[] numbers = {0, 0, 0, 1, 3, 3, 2, 1, 3, 5, 6, 0};
List<Integer> result = IntStream.of(numbers)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(e -> Stream.generate(e::getKey).limit(e.getValue()))
.flatMap(Function.identity())
.collect(Collectors.toList());
或者,如果您希望使用数组作为结果
int[] result = IntStream.of(numbers)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(e -> Stream.generate(e::getKey).limit(e.getValue()))
.flatMap(Function.identity())
.mapToInt(Integer::intValue)
.toArray();
答案 9 :(得分:0)
//根据频率对数组进行降序排序。
import java.util.*;
class sorting {
static int x = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0; i<n; i++){
a[i] = sc.nextInt();
}
Arrays.sort(a);
// l is number of distinct elements in array a.
int l=1;
for(int i=0; i<n-1; i++){
if(a[i]!=a[i+1]){
l++;
}
}
// creating a 2d array from a 1d array having elements and their frequencies.
int b[][] = new int[l][2];
b[x][0] = a[0];
int c=1;
for(int i=1; i<n; i++){
if(a[i]!=a[i-1]){
b[x][1]=c;
x++;
c=1;
b[x][0] = a[i];
}
else{
c++;
}
if(i==n-1){
b[x][1]=c;
}
}
// sorting 2d array according their frequencies.
for(int i=0; i<b.length; i++){
for(int j=i; j<b.length; j++){
if(b[i][1]<b[j][1]){
int t = b[i][1];
b[i][1] = b[j][1];
b[j][1] = t;
t = b[i][0];
b[i][0] = b[j][0];
b[j][0] = t;
}
}
}
for(int i=0; i<b.length; i++){
int k=b[i][1];
for(int j=0; j<k; j++){
System.out.print(b[i][0]+" ");
}
}
}
// bubble sort.
public static void sort(int a[]) {
int n = a.length;
for(int i=0; i<n; i++){
for(int j=i; j<n; j++){
if(a[i]>a[j]){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
}
答案 10 :(得分:0)
已经回答了,但是代码没有很好的解释。所以我将在这里尝试。
令要排序的数组为:int[] array = {4,4,2,2,2,2,3,3,1,1,6,7,5}
首先让我们计算每个数字的频率:
为此,我们将创建一个HashMap数据结构,该结构将把数组元素作为Key,并将其频率作为值。要存储我们的输出,我们将有一个输出列表。
HashMap<Integer,Integer> freqMap = new HashMap<>();
ArrayList<Integer> output = new ArrayList<>();
getOrDefault(key,defaultValue)
:这是一种处理场景的便捷方法,在这种情况下,我们希望返回的值不是null,无论何时找不到键,get方法都会返回该值。
进入代码:
for(int current : array)
{
int count = freqMap.getOrDefault(current,0); // if arrayelement is encountered first time it returns 0 otherwise it returns the actual count
freqMap.put(current,count++); // we increase the count by one and put it in the map
output.add(current); // we also add the element in the list.
}
现在,我们已经在HashMap中绘制了按其频率映射的元素。
- 2 comes four times
- 3 comes two times
- 4 comes two times
- 5,6 and 7 comes one time.
现在,我们需要根据频率对输出列表进行排序。为此,我们实现了comparator interface
。在此界面中,我们有一个方法
public int compare(Object obj1, Object obj2) //It compares the first object with the second object.
因此,我们创建了一个类SortComparator
来实现此接口,并创建了一个类comp
的对象SortComparator
。
SortComparator comp = new SortComparator(freqMap);
Collections.sort(output,comp);
for(Integer i : output)
{
System.out.print(i + " ");
}
这是Comparator接口的实现:
class SortComparator implements Comparator<Integer>
{
private final Map<Integer,Integer> freqMap;
SortComparator(Map<Integer,Integer>freqMap)
{
this.freqMap = freqMap;
}
public int compare(Integer k1,Integer k2)
{
//Comparing by frequency
int freqCompare = freqMap.get(k2).compareTo(freqMap.get(k1));
//Comparing by value
int valueCompare = k2.compareTo(k1);
if(freqCompare == 0)//frequency of both k1 and k2 is same then
{
return valueCompare;
}
else
{
return freqCompare;
}
}
答案 11 :(得分:0)
根据数组元素的频率对其排序
假设-
1.根据数组的自然出现以升序排序
2.如果两个具有相同频率的数字,则根据自然数优先级
示例:-[ 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5]
输出:-[ 5, 4, 4, 2, 2, 2, 3, 3, 3, 1, 1, 1, 1, 1]
解决方案:-
1 。创建一个HashMap,用于存储数组元素及其出现的位置
2 。将哈希图放入列表中,我们可以使用自定义比较器根据其频率进行排序
3 。对象比较是Java:-
如果Obj1
小于Obj2
,则返回-1
如果Obj1
等于Obj2
,则返回0
如果Obj1
更大,则Obj2然后返回+1
4 。在我们的例子中,如果两个数字具有相同的频率,则应在输出中放入自然优先级的数字
例如:-如果上面的示例中,数字2
和3
出现了3
次,因此2
应该排在首位
public static void sortTheArrayByFrequency(int[] array){
Map<Integer, Integer> map = new HashMap<>();
//put array elements based on its frequncies
for(int i : array){
map.put(i, map.getOrDefault(i,0)+1);
}
//Put the hashmap into a list where we use customized comparator
List<Map.Entry<Integer, Integer>> list = new ArrayList<>();
for(Map.Entry<Integer, Integer> e : map.entrySet()){
list.add(e);
}
// list looks like [1=5, 2=3, 3=3, 4=2, 5=1]
Collections.sort(list, (a, b) -> {
// if its ouccrances are same then sort natually
//else sort based on freqncies
if(a.getValue() == b.getValue())
return a.getKey() - b.getKey();
else
return a.getValue() - b.getValue();
});
// list looks like [5=1, 4=2, 2=3, 3=3, 1=5]
for(Map.Entry<Integer, Integer> e : list){
int num = e.getValue();
while(num!=0){
System.out.print(e.getKey()+ " ");
num--;
}
}
}
输出:-
5 4 4 2 2 2 3 3 3 1 1 1 1 1
答案 12 :(得分:0)
import java.util.*;
class SortArrayByFrequency
{
public static void main(String[] args)
{
int a[]={2,2,2,2,4,4,4,4,4,4,5,6,6,6,6,6,1,1,1};
int count=0;
int k[]=new int[10];// for elements
int v[]=new int[10];//store the frquency of corresponding element
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<a.length;i++)
{
if(map.containsKey(a[i]))
{
map.put(a[i],map.get(a[i])+1);
}
else
{
map.put(a[i],1);
}
}
Set<Integer> keys=map.keySet();
int i=0,j=0;
for(int key:keys){
//System.out.println(key+" : "+map.get(key));
v[i++]=map.get(key);
k[j++]=key;
}
System.out.println("--------------------");
//Sort the array which contains the frquency of elements
for(int f=0;f<i-1;f++){
//System.out.println(k[f]+" "+v[f]);
int min=f;
for(int g=f+1;g<i;g++)
{
if(v[min]>v[g])
{
min=g;
}
}
int temp=v[min];
v[min]=v[f];
v[f]=temp;
//here we swap the element according to sorting ------------
int temp1=k[min];
k[min]=k[f];
k[f]=temp1;
}
System.out.println("-----Array sort by frequency in ascending order------------");
for(int l=0;l<i;l++){
//System.out.println(v[l]+" :: "+k[l]);
for(int p=0;p<v[l];p++)
System.out.print(k[l]+" ");
}
}
}
升序
//输出:5 1 1 1 2 2 2 2 6 6 6 6 6 4 4 4 4 4 4 4
答案 13 :(得分:0)
使用Map,ArrayList和Comparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class OrderArrayFrequency {
public static void main(String[] args) {
int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
ConcurrentHashMap<Integer, Integer> counts = new ConcurrentHashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (counts.containsKey(nums[i])) {
Integer c = counts.get(nums[i]) + 1;
counts.put(nums[i], c);
} else {
counts.put(nums[i], 1);
}
}
ArrayList<Integer> list = new ArrayList<>();
for (Integer i : counts.keySet()) {
list.add(counts.get(i));
}
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2)
return -1;
return 0;
}
});
Set<Entry<Integer, Integer>> set = counts.entrySet();
for (Integer i : list) {
for (Entry<Integer, Integer> entry : set) {
if (entry.getValue().equals(i)) {
System.out.print(entry.getKey()+":"+entry.getValue()+ " ");
counts.remove(entry.getKey());
}
}
}
}
}
输出:2:1 5:1 6:1 1:2 3:3 0:4
答案 14 :(得分:0)
我是编码的新手,我使用“ for循环”进行了尝试。这是我的代码-
//Driver Program
public static void main(String args[])
{
int[] array = { 2, 2, 3, 4, 5, 12, 2, 3, 3, 3, 12 };
sortByCount(array);
}
//Array element's count
static int elementsCount(int ar[], int n)
{
int count = 0;
for(int i : ar)
{
int max = n;
if(i == max)
{
count++;
}
max = i;
}
return count;
}
//Ascending order sort by count
static void sortByCount(int ar[])
{
int temp = 0;
for(int i = 0; i < ar.length; i++)
{
for(int j = i + 1; j < ar.length; j++)
{
if(elementsCount(ar, ar[i]) > elementsCount(ar, ar[j]))
{
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
printArray(ar);
}
//Print Array
static void printArray(int[] ar)
{
for(int i : ar)
{
System.out.println(i);
}
}
答案 15 :(得分:0)
public class Frequency {
static int key;
public static void main(String[] args) {
Integer[] nums = { 7, 3, 4, 3, 4, 3, 4, 3, 6, 5, 7 };
Map<Integer, Integer> m1;
//Convert the integer array into an Array List.
ArrayList<Integer> numbers = new ArrayList<Integer>(Arrays.asList(nums));
//ArrayList to store the number of occurences of numbers.
List<Integer> values = new ArrayList<Integer>();
//ArrayList to show the array in requested order.
List<Integer> output = new ArrayList<Integer>();
m1 = new LinkedHashMap<Integer, Integer>();
for (int a : numbers) {
//Add data in Hash map where key is number and value is the total occurences of that number.
if (m1.containsKey(a)) {
int value = m1.get(a);
m1.put(a, ++value);
} else {
m1.put(a, 1);
}
}
System.out.println(m1);
for (Map.Entry<Integer, Integer> entry : m1.entrySet()) {
values.add(entry.getValue());
}
Collections.sort(values, Collections.reverseOrder());
System.out.println(values.toString());
for (int m = 0; m < values.size(); m++) {
for (Map.Entry<Integer, Integer> entry : m1.entrySet()) {
if (entry.getValue().equals(values.get(m))) {
key = entry.getKey();
System.out.println("Key is" + key);
for (int k = values.get(m); k > 0; k--) {
output.add(key);
}
break;
}
}
m1.remove(key);
}
System.out.println(output.toString());
}
}
答案 16 :(得分:0)
仅使用数组。
import java.util.*;
public class SortAccordingToFrequency {
public static void main(String[] args) {
int r;
int b[]={1,1,1,2,1,2,3,6,6,5};int i;int n=b.length;int k=0;
Arrays.sort(b);
int[] a=new int[n+1];
for(r=0;r<n;r++){
a[r]=b[r];}
a[r]=1882737378; //Any arbitrary value.
int c=1;int in[]=new int[10];
int[] e=new int[10];
for(i=0;i<n;i++){
if(a[i]==a[i+1])
c++;
else{
e[k]=a[i];
in[k]=c;k++;
c=1;
}
}
for (int f = 0; f < k; f++) {
for (int g = 0; g < k-f-1; g++) {
if (in[g] > in[g+1]){
int[] ans = swap(in[g], in[g+1]);
in[g]=ans[0];
in[g+1]=ans[1];
int[] an = swap(e[g], e[g+1]);
e[g]=an[0];
e[g+1]=an[1];
}
}
}
int d=0;
for(int x=0;x<k;x++){
for(int y=0;y<in[x];y++){
System.out.print(e[d]);
}d++;
}
}
static int[] swap(int n1,int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
int ans[]=new int[2];
ans[0]=n1;
ans[1]=n2;
return ans;
}
}
答案 17 :(得分:0)
我不喜欢上面的答案,所以我要添加我所做的。总体思路很简单-只需按Comparator
对列表进行排序,将哈希映射作为参数即可。
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] ar = new int[] {0,0,0,1,3,3,2,1,3,5,6,0};
Map<Integer,Integer> map = new HashMap<>();
List<Integer> output = new ArrayList<>();
for(int current : ar) {
int count = map.getOrDefault(current, 0);
map.put(current, count + 1);
output.add(current);
}
FrequencyComparator comp = new FrequencyComparator(map);
Collections.sort(output, comp);
for(Integer i : output){
System.out.print(i + " ");
}
}
}
还有FrequencyComparator
:
import java.util.Comparator;
import java.util.Map;
public class FrequencyComparator implements Comparator<Integer> {
private final Map<Integer,Integer> freqMap;
FrequencyComparator(Map<Integer,Integer> i_freqMap) { this.freqMap = i_freqMap; }
@Override
public int compare(Integer k1, Integer k2) {
int freqCompare = freqMap.get(k1).compareTo(freqMap.get(k2));
int valueCompare = k1.compareTo(k2);
// If frequency is equal, then just compare by value, otherwise - compare by the frequency.
if(freqCompare == 0)
return valueCompare;
else
return freqCompare;
}
}
输出:
2 5 6 1 1 3 3 3 0 0 0 0
答案 18 :(得分:0)
public class SortBasedOnFrequency {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arr = new String[] { "abc", "def", "qas", "abc", "abc", "def" };
new SortBasedOnFrequency().sort(arr);
}
void sort(String[] a) {
Map<String, Integer> map = new HashMap<>();
for (String s : a) {
//convert array to map putting key as the array element and value as the
//number of occurence.
map.put(s, map.get(s) == null ? 1 : map.get(s) + 1);
}
List<Map.Entry<String, Integer>> mapEntryList = new ArrayList<>map.entrySet());// sort mapEntry list based on value
Collections.sort(mapEntryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return o1.getValue().compareTo(o2.getValue());
}
});
//print the object in sorting order of the occurrence.
for (Entry<String, Integer> m : mapEntryList) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
答案 19 :(得分:0)
myTranslit :: String -> String
myTranslit = concatMap toAsciiStr
答案 20 :(得分:0)
import java.io.*;
import java.lang.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
class SortingFrequency
{
public static void main(String args[]) throws Exception{
int i,j,temp,temp1,count;
int []a=new int[10];
int []freq=new int[10];
Scanner s=new Scanner(System.in);
for(i=0;i<5;i++){
a[i]=s.nextInt();
freq[i]=-1;
}
for(i=0;i<5;i++)
{
count=1;
for(j=i+1;j<5;j++)
{
if(a[i]==a[j])
{
count++;
freq[j]=0;
}
}
if(freq[i]!=0)
{
freq[i]=count;
}
}
Map map=new HashMap();
for(i=0;i<5;i++){
if(freq[i]!=0){
map.put(a[i],freq[i]);
System.out.println("map elt"+map);
System.out.println("a"+a[i]+"fr"+freq[i]);
}
}
Set<Entry<Integer,Integer>> set=map.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<Integer, Integer>>()
{
public int compare( Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
});
for(Map.Entry<Integer, Integer> entry:list){
System.out.println(entry.getKey()+" ==== "+entry.getValue());
}
}
}
答案 21 :(得分:0)
以下程序有点冗长但很容易理解。希望这是你所期待的。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
int[] arra = {-2,-2,-2,-1,-1,-1,2,2,1,3,1,9,9,1,1,9,9};
for(int i:sortedArrary(arra)){
System.out.print(i+" ");
}
}
static int[] sortedArrary(int[] inputArray)
{
TreeMap<Integer,Integer> repetitiveElements = null;
if(inputArray==null || inputArray.length<=0)
return null;
repetitiveElements = new TreeMap<Integer,Integer>();
for(int i=0;i<inputArray.length;i++)
{
if(repetitiveElements.containsKey(inputArray[i]))
{
repetitiveElements.put(inputArray[i], repetitiveElements.get(inputArray[i])+1);
}else{
repetitiveElements.put(inputArray[i],1);
}
}
//System.out.println("repetitive "+repetitiveElements);
ArrayList<Integer> keysArray = new ArrayList<Integer>(repetitiveElements.size());
ArrayList<Integer> valuesArray = new ArrayList<Integer>(repetitiveElements.size());
int key;
Iterator<Integer> itr = repetitiveElements.keySet().iterator();
while(itr.hasNext())
{
key = itr.next();
keysArray.add(key);
valuesArray.add(repetitiveElements.get(key));
}
/*
System.out.println("keys "+keysArray);
System.out.println("values "+valuesArray);
*/
LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
int maxValue=-1;
int maxKey = -1;
int pos = -1;
for(int i=0;i<repetitiveElements.size();i++)
{
if(keysArray.get(i)==null)
continue;
maxKey = keysArray.get(i);
maxValue = valuesArray.get(i);
pos=i;
for(int j=0;j<repetitiveElements.size();j++)
{
if(valuesArray.get(j)!=null && maxValue>valuesArray.get(j))
{
maxValue = valuesArray.get(j);
maxKey = keysArray.get(j);
pos = j;
}else if(valuesArray.get(j)!=null && maxValue==valuesArray.get(j)){
if(keysArray.get(j)!=null && maxKey>keysArray.get(j))
{
maxKey = keysArray.get(j);
pos = j;
}
}
}
map.put(maxKey, maxValue);
valuesArray.set(pos, null);
keysArray.set(pos, null);
}
for(int i=0;i<keysArray.size();i++)
{
if(keysArray.get(i)!=null)
{
map.put(keysArray.get(i), valuesArray.get(i));
}
}
itr = map.keySet().iterator();
int count=0,value;
while(itr.hasNext())
{
key = itr.next();
value = map.get(key);
for(int i=0;i<value;i++)
{
inputArray[count++] = key;
}
}
return inputArray;
}
}
答案 22 :(得分:-1)
根据频率对数组进行排序:
public static void main(String[] args) {
int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
Map<Integer, Integer> mp = new LinkedHashMap<>();
List<Integer> res = new ArrayList<>();
int count = 1;
for (int i = 0; i < arr.length; i++) {
if (!mp.containsKey(arr[i])) {
mp.put(arr[i], count);
} else {
mp.put(arr[i], mp.get(arr[i]) + 1);
}
}
if (!mp.containsValue(2)) {
for (Integer ab : arr)
res.add(ab);
Collections.sort(res);
Collections.reverse(res);
System.out.println(res);
} else {
Set<Entry<Integer, Integer>> set = mp.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<>(set);
Collections.sort(list, new Comparator<Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> obj1, Entry<Integer, Integer> obj2) {
if (obj2.getValue() > obj1.getValue())
return 1;
if (obj2.getValue() < obj1.getValue())
return -1;
else
return 0;
}
});
for (Map.Entry<Integer, Integer> e : list) {
for (int i = 1; i <= e.getValue(); i++)
res.add(e.getKey());
}
System.out.println(res);
}
}
答案 23 :(得分:-1)
import java.util.Arrays;
import java.util.Comparator;
public class TestString {
public static void main(String[] args) {
int arrTemp[] = { 2, 2, 2, 1, 1, 4, 5, 6, 6, 7, 7, 7, 7 };
Arrays.sort(arrTemp);
Integer[][] sortedArray = new Integer[6][2];
int count = 0;
sortedArray[count][0] = arrTemp[0];
sortedArray[count][1] = 1;
for (int i = 0; i < arrTemp.length - 1; i++) {
for (int j = 1; j < arrTemp.length; j++) {
if (arrTemp[i] == arrTemp[j]) {
sortedArray[count][1] = sortedArray[count][1] + 1;
i = j;
} else {
++count;
sortedArray[count][0] = arrTemp[j];
sortedArray[count][1] = 1;
i = j;
}
}
}
Arrays.sort(sortedArray, new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[1].compareTo(o2[1]);
}
});
for (int row = 0; row < 6; row++) {
for (int col = 0; col < sortedArray[row][1]; col++) {
System.out.print(sortedArray[row][0] + " ");
}
}
}
}