【问题标题】:Sort objects by Group and Date, and keep only latest object in each Group按组和日期对对象进行排序,并仅保留每个组中的最新对象
【发布时间】:2021-05-14 10:38:21
【问题描述】:

一个对象至少包含 Group 和 Date 这两个字段

interface Object {
   group: Integer
   date: Date
   ...
}

然后给定一个由几个对象组成的数组

array: Objects[] <- getAllObjects()

在每个组中查找最新的对象。或者更通用:对于每个不同的组,提取最高值。

一种方法是按组映射对象,然后对于每个组,按降序对该组中的对象进行排序并提取第一个元素。

function takes Array: Objects[] returns Object[] begin
   
   map: Map<Group, Object[]> <- empty map

   for each Object in Array do
      if (map contains key Object.group) then
         objectArray <- get value by key Object.group from map
         add Object to objectArray
      else then
         objectArray <- empty array 
         add Object to objectArray
         add value objectArray to map with key Object.group
      end
   end

   returnArray: Objects[] <- empty array

   for each Group in Map
      objectArray <- get value by key Group from Map
      sort objectArray by Object.date, descending
      latestObjectInGroup <- pop objectArray
      add latestObjectInGroup to returnArray
   end

   return returnArray
end

我的问题是:是否有更简单(例如,不那么复杂、更简洁、不那么复杂)的算法来实现这个目标?可以使用任何编程语言或库,包括 Map/List 函数,例如 Sort、Reduce、Map、Filter、Collect 等。

【问题讨论】:

    标签: algorithm sorting


    【解决方案1】:

    你可以避免排序。

    使用 key=group value = objectWithHigestValueYet 创建地图

    并在您看到该组的更高值时更新该值。

    function takes Array: Objects[] returns Object[] begin
       
       map: Map<Group, Object[]> <- empty map
    
       for each Object in Array do
          if (map contains key Object.group) then
             oldHighestObject <- get value by key Object.group from map
             if(oldHighestObject.value<Object.value)         
               map.put(Object.group, Object)    // replace the old entry by this new one with higher value
          else then
             add value Object to map with key Object.group
          end
       end
    
       returnArray: Objects[] <- empty array
    
       for each Group in Map
          objec <- get value by key Group from Map
          add objec to returnArray
       end
    
       return returnArray
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多