package org.example.test;

import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class TopKstringsTest {
    public static void main(String[] args) {
        String[] test = {"a", "b", "c", "b"};
        System.out.println(JSONObject.toJSONString(topKstrings(test, 2)));
    }

    /**
     * 搞半天,没有灵活运用list排序和map.get()
     * @param strings
     * @param k
     * @return
     */
    public static String[][] topKstrings(String[] strings, int k) {
        // write code here
        SortedMap<String, Integer> map = new TreeMap<>();
        for (String str : strings) {
            map.put(str, map.getOrDefault(str, 0) + 1);
        }
        List<String> rec = new ArrayList<String>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            rec.add(entry.getKey());
        }
        Collections.sort(rec, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return map.get(o1) == map.get(o2) ? o1.compareTo(o2) : map.get(o2) - map.get(o1);
            }
        });
        int i = 0;
        String[][] topk = new String[k][2];
        for (String key : rec) {
            if (i >= k) {
                break;
            }
            topk[i][0] = key;
            topk[i][1] = String.valueOf(map.get(key));
            i++;
        }

        return topk;
    }
}