Given an integer array arr
, you need to sort the array in a specific order:
Return the sorted array.
1 <= arr.length <= 500
and 0 <= arr[i] <= 10^4
).1
bits. For example, bin(x).count('1')
.sorted()
function with a custom key that first sorts by the number of 1 bits and then by the integer value itself.10^4
can have at most 14 bits. Counting the bits is O(1)
for each number.n
is O(n log n)
.The overall time complexity will be dominated by the sorting step: O(n log n).
def sortByBits(arr):
# Define the custom sorting key
def sort_key(x):
return (bin(x).count('1'), x)
# Return the sorted array
return sorted(arr, key=sort_key)
# Example usage
arr = [0,1,2,3,4,5,6,7,8]
sorted_array = sortByBits(arr)
print(sorted_array) # Output: [0, 1, 2, 4, 8, 3, 5, 6, 7]
This code correctly implements the strategy and efficiently sorts the array based on the provided rules.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?