|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | + |
| 9 | +/** |
| 10 | + * 1356. Sort Integers by The Number of 1 Bits |
| 11 | + * |
| 12 | + * Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in |
| 13 | + * their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. |
| 14 | + * |
| 15 | + * Return the sorted array. |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * Input: arr = [0,1,2,3,4,5,6,7,8] |
| 19 | + * Output: [0,1,2,4,8,3,5,6,7] |
| 20 | + * Explantion: [0] is the only integer with 0 bits. |
| 21 | + * [1,2,4,8] all have 1 bit. |
| 22 | + * [3,5,6] have 2 bits. |
| 23 | + * [7] has 3 bits. |
| 24 | + * The sorted array by bits is [0,1,2,4,8,3,5,6,7] |
| 25 | + * |
| 26 | + * Example 2: |
| 27 | + * Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] |
| 28 | + * Output: [1,2,4,8,16,32,64,128,256,512,1024] |
| 29 | + * Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. |
| 30 | + * |
| 31 | + * Example 3: |
| 32 | + * Input: arr = [10000,10000] |
| 33 | + * Output: [10000,10000] |
| 34 | + * |
| 35 | + * Example 4: |
| 36 | + * Input: arr = [2,3,5,7,11,13,17,19] |
| 37 | + * Output: [2,3,5,17,7,11,13,19] |
| 38 | + * |
| 39 | + * Example 5: |
| 40 | + * Input: arr = [10,100,1000,10000] |
| 41 | + * Output: [10,100,10000,1000] |
| 42 | + * |
| 43 | + * Constraints: |
| 44 | + * 1 <= arr.length <= 500 |
| 45 | + * 0 <= arr[i] <= 10^4 |
| 46 | + * */ |
| 47 | +public class _1356 { |
| 48 | + public static class Solution1 { |
| 49 | + public int[] sortByBits(int[] arr) { |
| 50 | + Map<Integer, List<Integer>> map = new HashMap<>(); |
| 51 | + for (int num : arr) { |
| 52 | + int count = Integer.bitCount(num); |
| 53 | + if (!map.containsKey(count)) { |
| 54 | + map.put(count, new ArrayList<>()); |
| 55 | + } |
| 56 | + map.get(count).add(num); |
| 57 | + } |
| 58 | + int[] result = new int[arr.length]; |
| 59 | + int i = 0; |
| 60 | + for (int count : map.keySet()) { |
| 61 | + List<Integer> list = map.get(count); |
| 62 | + Collections.sort(list); |
| 63 | + for (int num : list) { |
| 64 | + result[i++] = num; |
| 65 | + } |
| 66 | + } |
| 67 | + return result; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments