Python 中的远距离条形码

pythonserver side programmingprogramming更新于 2023/10/5 8:33:00

假设仓库中有一排条形码。第 i 个条形码是 barcodes[i]。我们必须重新排列条形码,使相邻的条形码之间不相同。因此,如果输入是 [1,1,1,2,2,2],则输出是 [2,1,2,1,2,1]。

为了解决这个问题,我们将遵循以下步骤 −

  • 创建一个名为 d 的映射
  • 将条形码数组中出现的数字的频率存储到 d 中
  • x := 空列表
  • 将所有键值对插入 x
  • i := 0
  • res := 创建一个长度与条形码相同的列表,并填充 [0]
  • 根据频率对 x 进行排序
  • while i <结果的长度
    • result[i] := x 的最后一个条目的元素
    • 减少 x 的最后一个条目的频率值
    • 如果 x 的最后一个元素的频率为 0,则从 x 中删除该条目
    • 将 i 增加 2
  • i := 1
  • 当 i < 结果的长度
    • result[i] := x 的最后一个条目的元素
    • 减少 x 的最后一个条目的频率值
    • 如果 x 的最后一个元素的频率为 0,则从 x 中删除该条目
    • 将 i 增加 2
  • 返回 result

让我们看看下面的实现以便更好地理解 −

示例

class Solution(object):
   def rearrangeBarcodes(self, barcodes):
      d = {}
      for i in barcodes:
         if i not in d:
            d[i] = 1
         else:
            d[i]+=1
      x = []
      for a,b in d.items():
         x.append([a,b])
      i = 0
      result = [0]*len(barcodes)
      x = sorted(x,key=lambda v:v[1])
      while i <len(result):
         result[i] = x[-1][0]
         x[-1][1]-=1
         if x[-1][1]==0:
            x.pop()
         i+=2
      i=1
      while i <len(result):
         result[i] = x[-1][0]
         x[-1][1]-=1
         if x[-1][1]==0:
            x.pop()
         i+=2
      return result
ob = Solution()
print(ob.rearrangeBarcodes([1,1,1,2,2,2]))

输入

[1,1,1,2,2,2]

输出

[2, 1, 2, 1, 2, 1]

相关文章