Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
下面1002的代码还能怎么优化?我开始使用了java中的TreeMap解决1002题,但是要用时5000ms左右,后来采用了HashMap,也要将近4000ms左右,我想知道我的代码应该怎么优化?代码如下: public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testNum = Integer.parseInt(scanner.nextLine()); HashMap<String, Integer> map = new HashMap<String, Integer>(); char[] array = new char[7]; for (int i = 0; i < testNum; i++) { String line = scanner.nextLine(); int index = 0; for (int j = 0; j < line.length(); j++) { char c = line.charAt(j); if (c >= 'A' && c <= 'R') array[index++] = (char) ((2 + (c - 'A') / 3) + '0'); else if (c == 'S') array[index++] = '7'; else if (c >= 'T' && c <= 'Y') array[index++] = (char) ((8 + (c - 'T') / 3) + '0'); else if (c >= '0' && c <= '9') array[index++] = c; } String key = String.valueOf(array); if (map.containsKey(key)) map.put(key, map.get(key) + 1); else map.put(key, 1); } ArrayList<String> list = new ArrayList<String>(map.keySet()); Collections.sort(list); StringBuilder sbBuilder = new StringBuilder(); for (String key : list) if (map.get(key) != 1) sbBuilder.append(key.substring(0, 3)).append('-') .append(key.substring(3)).append(' ') .append(map.get(key)).append('\n'); if (sbBuilder.length() < 3) System.out.println("No duplicates."); else System.out.println(sbBuilder); } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator