The title
I give you an integer array arr. You sort the elements of the array in ascending order by the number of digits 1 in their binary representation.
If there are multiple numeric binaries with the same number of 1s, they must be sorted in ascending numerical order.
Please return the sorted array.
Example 1: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explanation: [0] is the only number that has zero ones. [1,2,4,8] all have a 1. [3,5,6] we have two ones. [7] There are three ones. In accordance with the number 1 for sorting the results array [0,1,2,4,8,3,5,6,7] example 2: input: arr =,64,32,16,8,4,2,1 [1024512256128] output: ,2,4,8,16,32,64,128,256,512,1024 [1] : all integer in the array only one 1 under the binary, so you need to sort them according to the numerical size. Example 3: input: arr = [10000,10000] output: [10000,10000] example 4: input: arr = [2,3,5,7,11,13,17,19] output: [2,3,5,17,7,11,13,19] example 5: input: Arr = [10,100,1000,10000] output: [10,100,10000,1000]Copy the code
Tip:
1 <= arr.length <= 500 0 <= arr[i] <= 10^4
Their thinking
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: From collections import Counter # bin is used to convert characters into binary # Counter to collect how many 1 # forms (values, TupleList = [(x,(dict(Counter(bin(x)))). Get ("1",0)) for x in arr] # resTupleList = sorted(tupleList, key= lambda x: (x[1], x[0])) # print(resTupleList) resList = [x for x, _ in resTupleList] # print(resList) return resList if __name__ == '__main__': Arr =,64,32,16,8,4,2,1 [1024512256128] arr = [0, 1, 2, 3, 4, 5, 6, 7, 8] ret = Solution () sortByBits (arr) print (ret)Copy the code