贪心算法(18)(java)距离相等的条形码

在一个仓库里,有一排条形码,其中第 i 个条形码为 barcodes[i]

请你重新排列这些条形码,使其中任意两个相邻的条形码不能相等。 你可以返回任何满足该要求的答案,此题保证存在答案。

示例 1:

复制代码
输入:barcodes = [1,1,1,2,2,2]
输出:[2,1,2,1,2,1]

示例 2:

复制代码
输入:barcodes = [1,1,1,1,2,2,3,3]
输出:[1,3,1,3,2,1,2,1]

解法:贪心+模拟

1.每次处理一批相同的数。

2.摆放的时候,每次隔一个格子。

3。先处理出现次数最多的那个数,剩下的处理顺序无所谓;

java 复制代码
import java.util.HashMap;
import java.util.Map;
public class Solution {
    public int[] rearrangeBarcodes(int[] barcodes) {
        Map<Integer,Integer>hash=new HashMap<>();//统计每个数字出现了多少次
        int maxVal=0,maxCount=0;
        for (int x:barcodes)
        {
            hash.put(x,hash.getOrDefault(x,0)+1);
            if (maxCount<hash.get(x))
            {
                maxVal=x;
                maxCount=hash.get(x);
            }
        }
        int n= barcodes.length;
        int[] ret =new int[n];
        int index=0;
        //先处理出现次数最多的那个数
        for (int i=0;i<maxCount;i++)
        {
            ret[index]=maxVal;
            index +=2;
        }
       hash.remove(maxVal);
        for (int x:hash.keySet())
        {
            for (int i=0;i<hash.get(x);i++)
            {
                if (index>=n)index=1;
                ret[index]=x;
                index +=2;
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        Solution solution=new Solution();
        int[] barcodes={1,1,1,1,2,2,3,3};
        int[] result=solution.rearrangeBarcodes(barcodes);
        for (int num:result)
        {
            System.out.print(num+"");
        }
    }
}
相关推荐
hqxstudying1 分钟前
Java向量化
java·开发语言
李永奉22 分钟前
C语言-字符串(定义)、字符串函数(strlen、strcat、strcpy、strcmp、strlwr、strupr)
c语言·开发语言·算法
暖苏23 分钟前
python-异常(笔记)
大数据·开发语言·笔记·python·异常
Chase_______36 分钟前
JavaWeb笔记2-JavaScript&Vue&Ajax
开发语言·javascript·vue.js
●VON36 分钟前
重生之我在暑假学习微服务第七天《微服务之服务治理篇》
java·学习·微服务·云原生·nacos·架构·springcloud
你知道烟火吗1 小时前
谈谈对反射的理解?
java·开发语言·spring boot·后端
我爱996!1 小时前
Spring IoC&DI
java·后端·spring
啊阿狸不会拉杆1 小时前
《Java 程序设计》核心知识点梳理与深入探究
java·开发语言·python·算法·php·intellij-idea
三小尛1 小时前
C++拷贝构造函数
开发语言·c++
源力祁老师1 小时前
外部系统获取Odoo数据最便捷的方式
开发语言·前端·javascript