Skip to content

Commit 17a1cff

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 14.2 MB (79.63%)
1 parent a15bb2d commit 17a1cff

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>You are given an integer array <code>arr</code>. Sort the integers in the array&nbsp;in ascending order by the number of <code>1</code>&#39;s&nbsp;in their binary representation and in case of two or more integers have the same number of <code>1</code>&#39;s you have to sort them in ascending order.</p>
2+
3+
<p>Return <em>the array after sorting it</em>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> arr = [0,1,2,3,4,5,6,7,8]
10+
<strong>Output:</strong> [0,1,2,4,8,3,5,6,7]
11+
<strong>Explantion:</strong> [0] is the only integer with 0 bits.
12+
[1,2,4,8] all have 1 bit.
13+
[3,5,6] have 2 bits.
14+
[7] has 3 bits.
15+
The sorted array by bits is [0,1,2,4,8,3,5,6,7]
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> arr = [1024,512,256,128,64,32,16,8,4,2,1]
22+
<strong>Output:</strong> [1,2,4,8,16,32,64,128,256,512,1024]
23+
<strong>Explantion:</strong> All integers have 1 bit in the binary representation, you should just sort them in ascending order.
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= arr.length &lt;= 500</code></li>
31+
<li><code>0 &lt;= arr[i] &lt;= 10<sup>4</sup></code></li>
32+
</ul>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
public:
3+
vector<int> sortByBits(vector<int>& arr) {
4+
sort(arr.begin(), arr.end(), [](int x, int y) {
5+
int bx = __builtin_popcount(x);
6+
int by = __builtin_popcount(y);
7+
if (bx != by) return bx < by;
8+
return x < y;
9+
});
10+
return arr;
11+
}
12+
};
13+

0 commit comments

Comments
 (0)