HDU-1004 Let the Balloon Rise 解题报告

题目大概要求就是找到输入次数最多的字符串

需要注意输入格式为当输入n=0时结束程序

题目很简单,用Set或Map都能迅速解决

每组不超过1000的输入量,使得只要不是进入死循环,几乎不会出现超时的现象。

代码:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n;
		while (true) {
			n = sc.nextInt();
			if (n == 0) {
				break;
			}
			int maxN = 0;
			String maxS = null;
			String s = null;
			Map<String, Integer> map = new HashMap<>();
			for (int i = 0; i < n; i++) {
				s = sc.next();
				Integer v = map.get(s);
				if(v == null){
					v = 1;
				}else {
					v++;
				}
				if(v > maxN){
					maxN = v;
					maxS = s;
				}
				map.put(s, v);
			}
			System.out.println(maxS);
		}
	}
}

然后我又用数组做了一遍,发现我写的数组的速度竟然比Map还快,真是尴尬。

代码:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n;
		while (true) {
			n = sc.nextInt();
			if (n == 0) {
				break;
			}
			int num = 0;
			int maxN = 0;
			String maxS = null;
			String[] str = new String[1005];
			int[] strN = new int[1005];
			String s = null;
			for (int i = 0; i < n; i++) {
				int j;
				s = sc.next();
				for (j = 0; j < num; j++) {
					if(str[j].equals(s)){
						break;
					}
				}
				if (j == num) {
					str[j] = s;
					strN[j] = 1;
					num++;
				}else{
					strN[j]++;
				}
				if (strN[j] > maxN) {
					maxN = strN[j];
					maxS = s;
				}
			}
			System.out.println(maxS);
		}
	}
}

最后,本人菜鸡一枚,如果发现我的任何代码或理解有问题的话,欢迎指出讨论。(笑)

猜你喜欢

转载自blog.csdn.net/Timo_Max/article/details/81624908