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
对 barcodes 里相同的数字进行计数, 然后每次挑选数量最多的数字放置到答案中,同时检查该数字是不是答案中前一个数字相同,如果相同则取出数量第二多的数字放到答案中, 放置的数字数量-1
use std::collections::BinaryHeap;
impl Solution {
pub fn rearrange_barcodes(mut barcodes: Vec<i32>) -> Vec<i32> {
barcodes.sort();
let mut heap = BinaryHeap::new();
let mut prev = barcodes[0];
let mut count = 1;
for &code in barcodes[1..].into_iter() {
if prev != code {
heap.push((count, prev));
prev = code;
count = 1;
continue;
}
count += 1;
}
heap.push((count, prev));
let mut ans = Vec::new();
while let Some((c, v)) = heap.pop() {
if let Some(&last) = ans.last() {
if v == last {
let (nc, nv) = heap.pop().unwrap();
ans.push(nv);
if nc > 1 {
heap.push((nc - 1, nv));
}
heap.push((c, v));
continue;
}
ans.push(v);
if c > 1 {
heap.push((c - 1, v));
}
continue;
}
ans.push(v);
if c > 1 {
heap.push((c - 1, v));
}
}
ans
}
}