Re: [閒聊] 每日LeetCode

看板Marginalman作者 (溢傷了喇)時間6月前 (2023/11/03 03:27), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串484/719 (看更多)
: 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...啊...有機會再補 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.227.209.225 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1698953246.A.4C3.html
文章代碼(AID): #1bG_WUJ3 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bG_WUJ3 (Marginalman)