LeetCode 1054 Distant Barcodes (排序 贪心)

244 篇文章 0 订阅
34 篇文章 3 订阅

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

题目链接:https://leetcode.com/problems/distant-barcodes/

题目大意:重排数组使相邻元素不等,保证有解

题目分析:因为保证有解,可以省去一些不必要的判断,分奇偶位放数字,容易想到最优的方案是先选频数大的数字放

17ms,时间击败92.66%

class Solution {
    
    class Data {
        int freq, val;
        Data(int freq, int val) {
            this.freq = freq;
            this.val = val;
        }
    }
    
    public int[] rearrangeBarcodes(int[] barcodes) {
        int[] ans = new int[barcodes.length];
        int[] cnt = new int[10001];
        int sz = 0;
        for (int num : barcodes) {
            if (cnt[num] == 0) {
                sz++;
            }
            cnt[num]++;
        }
        
        Data[] d = new Data[sz];
        sz = 0;
        
        for (int num = 1; num < 10001; num++) {
            if (cnt[num] != 0) {
               d[sz++] = new Data(cnt[num], num);
            }
        }
        Arrays.sort(d, (Data a, Data b) -> (b.freq - a.freq));
        // for (int j = 0; j < sz; j++) {
        //     System.out.println(d[j].val + " " + d[j].freq);
        // }
        int i = 0, idx = 0;
        while (i < sz) {
            if (idx >= barcodes.length) {
                idx = 1;
            }

            if (d[i].freq == 0) {
                i++;
            }

            if (i < sz) {
                ans[idx] = d[i].val;
                d[i].freq--;
                idx += 2;
            }
        }
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值