🔗 🟢 1356. Sort Integers by The Number of 1 Bits

Problem Statement

題目簡述

給定整數陣列 arr\textit{arr},將其依照二進位表示中 11 的個數由小到大排序;若 11 的個數相同,則依數值由小到大排序。回傳排序後的陣列。

Constraints

約束條件

  • 1≤arr.length≤5001 \le \textit{arr.length} \le 500
  • 0≤arr[i]≤1040 \le \textit{arr}[i] \le 10^4

思路:多關鍵字排序

排序規則有兩層:先比 popcount(二進位中 11 的個數),相同時再比數值本身。這正是字典序比較的定義,因此把每個數 xx 映射成二元組

(popcount⁡(x), x)\big(\operatorname{popcount}(x),\ x\big)

作為排序鍵,直接排序即可。Python 中 int.bit_count() 可在常數時間取得 popcount。

複雜度分析

  • 時間複雜度:O(nlog⁡n)\mathcal{O}(n \log n),其中 nn 為 arr\textit{arr} 的長度。
  • 空間複雜度:O(n)\mathcal{O}(n),排序鍵與排序所需的額外空間。

Code

1
2
3
4
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
arr.sort(key=lambda x: (x.bit_count(), x))
return arr