小数据量用全量排序 + 向前过滤的情况。采出来的位置置为null;

    1. 2021.10.19
    2. 假设有一些系列的资源,每个资源有自己的id(int)、scoredoule)、typestr),
    3. 将其按score降序排序,尽量推荐给用户score高的资源;但是要求连续6条资源的type互不相同
    4. 输入: "\t"分隔, 每行一个资源:id, score, type
    5. 输出:推荐给用户的top 10的结果
    6. step1 : 确定type类型,每一类用最大堆结构维护
    7. public static class Item{
    8. int id;
    9. double socre;
    10. String str;
    11. // 构造函数
    12. }
    13. //构建候选资源池子
    14. public static void process(Item[] items ){
    15. HashMap<String, PriorityQueue<Item>> map = new HashMap();
    16. for(int i = 0 ;i < item.length; i++){
    17. if(map.containsKey(item.type)){
    18. PriorityQueue<Item> temp = map.get(items[i].type);
    19. temp.add(items[i]);
    20. }else{
    21. PriorityQueue<Item> temp = new LinkedList(new MyCompara);
    22. temp.add(items[i]);
    23. map.put(items[i].type, temp);
    24. }
    25. }
    26. }
    27. step2: 对每一个列表按照score大小排序,也可以将初始化的数据结构改成最小堆PriorityQueue
    28. step3 轮询采样。
    29. public static Item[] invoke(Map<String, List<Item>> map){
    30. Item[] result = second(map, 10, 6)
    31. }
    32. public static Item[] second(Map<String, List<Item>> map, int n, int diff ) {
    33. PriorityQueue<Item> maxScoreQueue= new PriorityQueue();
    34. for(int i = 0 ; i < Math.min(diff, map.size()); i ++){
    35. PriorityQueue curQueue = map.get(i);
    36. maxScoreQueue.add(curQueue.poll());
    37. }
    38. Item[] result = new Item(n);
    39. //尽可能按score由大到小,同时品类隔离。
    40. int index = 0;
    41. while(index < n){
    42. String[] sequeceType = new String[diff];
    43. if(index< diff){
    44. Item curItem = maxScoreQueue.poll()
    45. result[index++] = curItem;
    46. sequenceType[index] = curItem.type;
    47. }else{
    48. String firstType = sequenceType[0];
    49. Item attachItem = map.get(firstType).poll;
    50. }
    51. }
    52. // 如果不足,需要补足;
    53. if(index < n){
    54. for(int i = 0 ; i < map.size(); i ++){
    55. PriorityQueue curQueue = map.get(i);
    56. maxScoreQueue.add(curQueue.poll());
    57. }
    58. while(index < n ){
    59. if(!maxScoreQueue.isEmpty()){
    60. result[index++] = maxScoreQueue.poll();
    61. }else break;
    62. }
    63. }
    64. }