Re: [閒聊] 每日LeetCode

作者: z2147483648 (溢傷了喇)   2023-11-03 03:27:24
: https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/description
: 1356. Sort Integers by The Number of 1 Bits
: 給你一堆數字,依照二進位制的1的數量升序排序,如果數量一樣就比較數字本身。
以為有什麼規則,結果找半天想試DP什麼的也失敗
偷看解答才發現只是排序(;一:)
排序再搭配一個bit找1的數字的特性
練習了sort自定義lambda function的寫法
========== Python
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
arr.sort(key = lambda x: (self.countBits(x), x))
return arr
def countBits(self, num):
count = 0
while(num != 0):
num &= (num - 1)
count += 1
return count
========== C++
class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(), arr.end(), compare);
return arr;
}
static bool compare(int a, int b)
{
if (countBits(a) == countBits(b))
{
return a < b;
}
else
{
return countBits(a) < countBits(b);
}
}
static int countBits(int num)
{
int count = 0;
while(num != 0)
{
num &= (num - 1);
count++;
}
return count;
}
};
沒想到quick sort...啊...有機會再補

Links booklink

Contact Us: admin [ a t ] ucptt.com