一开始写的时对整个list进行sort操作,然后取前k和后k个输出,超时了。
各位大佬,拜托帮忙看看现在这种时间复杂度会不会超时。或者有没有比较好的做法。
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); HashMap<String, Integer> hashMap = new HashMap<>(); ArrayList<NodeT> big = new ArrayList<>(); ArrayList<NodeT> small = new ArrayList<>(); for (int i = 0; i < n; i++) { String s = in.next(); hashMap.put(s, hashMap.getOrDefault(s, 0) + 1); } for (String key : hashMap.keySet()) { NodeT t = new NodeT(); t.str = key; t.count = hashMap.get(key); big.add(t); paixu(big); if (big.size()> k)//去除最小的一个 big.remove(big.size()-1); small.add(t); paixu(small); if (small.size()>k)//去除最大的一个 small.remove(0); } for (NodeT t : big) System.out.println(t.str + " " + t.count); for (NodeT t : small) System.out.println(t.str + " " + t.count); } public static void paixu(ArrayList<NodeT> list){ Collections.sort(list, new Comparator<NodeT>() { @Override public int compare(NodeT nodeT1, NodeT nodeT2) { int len1 = nodeT1.str.length(); int len2 = nodeT2.str.length(); int len = Math.min(len1, len2); for (int i = 0; i < len; i++) { if (nodeT1.str.charAt(i) - nodeT2.str.charAt(i) > 0) { return 1; } else if (nodeT1.str.charAt(i) - nodeT2.str.charAt(i) < 0) { return -1; } } if (len1 > len2) { return 1; } else { return -1; } } }); } } class NodeT { String str; int count; }
全部评论
(1) 回帖