1.
一组数据输出出现次数最多的数据,如果出现次数相同的话,输出那个值比较大的数
第一种方法以空间换时间,时间复杂度O(n),空间复杂度O(n)
/**
一组数据输出出现次数最多的数据,如果出现次数相同,则输出值比较大的数
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int n = in.nextInt();
// 以空间换时间
int[] a = new int[n];
int[] count = new int[1000]; //存储a数组出现的次数
for(int i = 0;i<a.length;i++) {
a[i] = in.nextInt();
}
for(int i = 0;i<a.length;i++) {
count[a[i]]++;
}
int max = Integer.MIN_VALUE;
int maxV = Integer.MIN_VALUE;
for(int j = 0;j<count.length;j++) {
if(count[j]>max) {
max = count[j];
}
}
for(int i = 0; i <count.length ; i++) // 找出出现最多次的那个数字
{
if(count[i] == max) {
maxV = i;
}
}
System.out.println(maxV);
}
}
第二种方法运用HashMap
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int n = in.nextInt();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0;i<n;i++) {
int num = in.nextInt();
if(map.containsKey(num)) {
map.put(num, map.get(num)+1);
}else {
map.put(num, 1);
}
}
int max = Integer.MIN_VALUE; //存数
int maxV = Integer.MIN_VALUE;//存数出现的次数
for(Integer key : map.keySet()) {
if(map.get(key)>maxV) {
maxV = map.get(key);
}
}
for(Integer key : map.keySet()) {
if(map.get(key) == maxV && key>max) {
max = key;
}
}
System.out.println(max);
}
}
2.
1.运用包类方法,对数组进行按要求排序
Arrays.sort(a); //正向排序(从小到大)
Arrays.sort(a,Collections.reverseOrder()); //反向排序(从大到小)
// 字符串排序,先大写后小写
String[] strArray = new String[] { "z", "a", "C" };
Arrays.sort(strArray);
输出: [C, a, z]
//严格按字母表顺序排序,也就是忽略大小写排序 Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
输出: [a, C, z]
// 反向排序, Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
输出:[z, a, C]
// 忽略大小写反向排序 Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
输出: [z, C, a]
第二,构建比较器进行排序
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
Integer[] a = {1,4,3,5,2};
Arrays.sort(a,new RCompartor());
for(Integer num:a) { System.out.print(num+" ");}
}
}
class RCompartor implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2-o1;
}
}
暂且写到这里,之后不断成长继续增加,加油