@@ -46,8 +46,7 @@ The sorted array by bits is [0,1,2,4,8,3,5,6,7]
46
46
``` python
47
47
class Solution :
48
48
def sortByBits (self , arr : List[int ]) -> List[int ]:
49
- arr.sort(key = lambda x : (x.bit_count(), x))
50
- return arr
49
+ return sorted (arr, key = lambda x : (x.bit_count(), x))
51
50
```
52
51
53
52
### ** Java**
@@ -56,18 +55,94 @@ class Solution:
56
55
class Solution {
57
56
public int [] sortByBits (int [] arr ) {
58
57
int n = arr. length;
59
- for (int i = 0 ; i < n; i ++ ) {
58
+ for (int i = 0 ; i < n; ++ i ) {
60
59
arr[i] += Integer . bitCount(arr[i]) * 100000 ;
61
60
}
62
61
Arrays . sort(arr);
63
- for (int i = 0 ; i < n; i ++ ) {
62
+ for (int i = 0 ; i < n; ++ i ) {
64
63
arr[i] %= 100000 ;
65
64
}
66
65
return arr;
67
66
}
68
67
}
69
68
```
70
69
70
+ ``` java
71
+ class Solution {
72
+ public int [] sortByBits (int [] arr ) {
73
+ int n = arr. length;
74
+ Integer [] t = new Integer [n];
75
+ for (int i = 0 ; i < n; ++ i) {
76
+ t[i] = arr[i];
77
+ }
78
+ Arrays . sort(t, (a, b) - > {
79
+ int x = Integer . bitCount(a), y = Integer . bitCount(b);
80
+ return x == y ? a - b : x - y;
81
+ });
82
+ for (int i = 0 ; i < n; ++ i) {
83
+ arr[i] = t[i];
84
+ }
85
+ return arr;
86
+ }
87
+ }
88
+ ```
89
+
90
+ ### ** C++**
91
+
92
+ ``` cpp
93
+ class Solution {
94
+ public:
95
+ vector<int > sortByBits(vector<int >& arr) {
96
+ for (int& v : arr) {
97
+ v += __ builtin_popcount(v) * 100000;
98
+ }
99
+ sort(arr.begin(), arr.end());
100
+ for (int& v : arr) {
101
+ v %= 100000;
102
+ }
103
+ return arr;
104
+ }
105
+ };
106
+ ```
107
+
108
+ ```cpp
109
+ class Solution {
110
+ public:
111
+ vector<int> sortByBits(vector<int>& arr) {
112
+ sort(arr.begin(), arr.end(), [&](auto& a, auto& b) -> bool {
113
+ int x = __builtin_popcount(a), y = __builtin_popcount(b);
114
+ return x < y || (x == y && a < b);
115
+ });
116
+ return arr;
117
+ }
118
+ };
119
+ ```
120
+
121
+ ### ** Go**
122
+
123
+ ``` go
124
+ func sortByBits (arr []int ) []int {
125
+ for i , v := range arr {
126
+ arr[i] += bits.OnesCount (uint (v)) * 100000
127
+ }
128
+ sort.Ints (arr)
129
+ for i := range arr {
130
+ arr[i] %= 100000
131
+ }
132
+ return arr
133
+ }
134
+ ```
135
+
136
+ ``` go
137
+ func sortByBits (arr []int ) []int {
138
+ sort.Slice (arr, func (i, j int ) bool {
139
+ a , b := bits.OnesCount (uint (arr[i])), bits.OnesCount (uint (arr[j]))
140
+ return a < b || (a == b && arr[i] < arr[j])
141
+ })
142
+ return arr
143
+ }
144
+ ```
145
+
71
146
### ** TypeScript**
72
147
73
148
``` ts
0 commit comments