关于数组算法的一些总结

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;
		}
		
	}
	

暂且写到这里,之后不断成长继续增加,加油

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值