Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.
Have you met this question in a real interview?
Yes
Example
Given colors=[3, 2, 2, 1, 4]
, k=4
, your code should sort colors in-place to [1, 2, 2, 3, 4]
.
Note
You are not suppose to use the library's sort function for this problem.
Challenge
A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory. Can you do it without using extra memory?
Solution:
public void sortColors2(int[] colors, int k) { int n = colors.length; int[] B = new int[n]; int[] C = new int[k+1]; for(int a:colors) C[a]++; for(int i=1; i<=k; i++) { C[i] += C[i-1]; } for(int a:colors) { C[a]--; B[C[a]] = a; } System.arraycopy(B, 0, colors, 0, n); }
Reference:
https://zh.wikipedia.org/wiki/计数排序
http://www.geeksforgeeks.org/counting-sort/
https://www.cs.usfca.edu/~galles/visualization/CountingSort.html
相关推荐
462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/...
技术运维-机房巡检表及巡检说明
第四次算法分析与设计整理
图像处理项目实战
该资源为jaxlib-0.4.18-cp311-cp311-macosx_11_0_arm64.whl,欢迎下载使用哦!
搭建说明. 运行环境 php5.6 mysql5.6 扩展sg11 前置条件: 前后端分离,需要准备两个域名,一个后台域名,一个前端域名 后端源码修改(cs2.ijiuwu.com批量替换改为你的后端域名)数据库修改(cs3.ijiuwu.com批量替换为你的前端域名)1、创建后台站点,上传后台源码并解压到根目录2、创建前端站点,上传前端源码并解压到根目录 3、创建数据库上传并导入数据库文件 4、修改数据库信息: 后台:app/database.php 前端:application/database.php 前端站点设置 伪静态thinkphp 运行目录public 关闭防跨站 访问后台域名/admin.php进入后台管理 admin 123456 系统-》系统设置-》附件设置-》Web服务器URL 改为你的前端域名 系统-》清前台缓存 改为你的前端域名 点击刷新缓存
【毕业答辩】爆款黑板风教育文艺毕业论文答辩通用模板.pptx
1、文件内容:systemd-devel-219-78.el7_9.9.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/systemd-devel-219-78.el7_9.9.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、更多资源/技术支持:公众号禅静编程坊
win32汇编环境,对 WM-MOUSEMOVE 消息的理解
车牌识别项目
UE项目开发过程中的一些快捷脚本
lab1的words.txt文件
python、yolo、pytorch
人工智能、大语言模型相关学习资料
图像处理项目实战
python、yolo、pytorch
车牌识别项目
该资源为jaxlib-0.4.18-cp312-cp312-macosx_10_14_x86_64.whl,欢迎下载使用哦!
python、yolo、pytorch
Swift-IOS TODO_List应用开发