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