Python程式:查詢售出n件商品後剩餘商品數量
假設我們有一個名為items的數字列表和另一個值n。一位銷售人員在一個包裡裝有隨機ID的商品。銷售人員可以從包中刪除多達n件商品。我們必須找到刪除n件商品後包中不同ID的最小數量。
因此,如果輸入類似於items = [2, 2, 6, 6] n = 2,則輸出將為1,因為我們可以出售兩件ID為2或ID為6的商品,然後只剩下具有單個目標的商品。
為了解決這個問題,我們將遵循以下步驟
- c := items中每個元素的頻率
- ans := c的大小
- freq := 對c中所有頻率的列表進行排序
- i := 0
- 當 i < freq的大小 時,執行:
- 如果 freq[i] <= n,則
- n := n - freq[i]
- ans := ans - 1
- 否則
- 返回 ans
- i := i + 1
- 如果 freq[i] <= n,則
- 返回 0
讓我們看看下面的實現以更好地理解
示例
from collections import Counter class Solution: def solve(self, items, n): c = Counter(items) ans = len(c) freq = sorted(c.values()) i = 0 while i < len(freq): if freq[i] <= n: n -= freq[i] ans -= 1 else: return ans i += 1 return 0 ob = Solution() items = [2, 2, 6, 6] n = 2 print(ob.solve(items, n))
輸入
[2, 2, 6, 6], 2
輸出
1
廣告