All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1001_1100.s1054_distant_barcodes.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g1001_1100.s1054_distant_barcodes;

// #Medium #Array #Hash_Table #Sorting #Greedy #Heap_Priority_Queue #Counting
// #2022_02_28_Time_45_ms_(64.21%)_Space_69.1_MB_(71.24%)

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 1054 - Distant Barcodes\.
 *
 * Medium
 *
 * In a warehouse, there is a row of barcodes, where the ith barcode is `barcodes[i]`.
 *
 * Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
 *
 * **Example 1:**
 *
 * **Input:** barcodes = [1,1,1,2,2,2]
 *
 * **Output:** [2,1,2,1,2,1]
 *
 * **Example 2:**
 *
 * **Input:** barcodes = [1,1,1,1,2,2,3,3]
 *
 * **Output:** [1,3,1,3,1,2,1,2]
 *
 * **Constraints:**
 *
 * *   `1 <= barcodes.length <= 10000`
 * *   `1 <= barcodes[i] <= 10000`
**/
public class Solution {
    public int[] rearrangeBarcodes(int[] barcodes) {
        Map cnt = new HashMap<>();
        for (int i : barcodes) {
            cnt.put(i, cnt.getOrDefault(i, 0) + 1);
        }
        List> list = new ArrayList<>(cnt.entrySet());
        list.sort(Map.Entry.comparingByValue().reversed());
        int l = barcodes.length;
        int i = 0;
        int[] res = new int[l];
        for (Map.Entry e : list) {
            int time = e.getValue();
            while (time-- > 0) {
                res[i] = e.getKey();
                i += 2;
                if (i >= barcodes.length) {
                    i = 1;
                }
            }
        }
        return res;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy