75. Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

三种颜色,把颜色排序,按照红、白、蓝的顺序,其中颜色对应的是0,1,2.


代码:


参考代码

解题思路:两个指针 i0,i2,for循环遍历,如果遇到的数字是2,那么和末尾i2指向的交换,然后i2向前移动一位,如果交换后仍然是2,那么继续交换移位;如果nums[i]是0,那么和i0指向的位置交换,然后i0向后移动一位;最后如果i已经和i2重合,说明遍历结束。


运行结果展示:


测试

Sort Colors

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容