【075-Sort Colors (颜色排序)】


【LeetCode-面试算法经典-Java实现】【全部题目文件夹索引】

原题

  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.

  Note:

  You are not suppose to use the library’s sort function for this problem.

题目大意

  给定一个对象数组,对象是红色,白色和蓝色,对颜色进行排序。红。白,蓝。

  使用0,1,2分别代表红,白,蓝。

  注意:不能使用库函数进行排序。

解题思路

  对数组进行扫描,计录1的个数和整个数组的和。扫描完后能够得出1的数目t。2的数目(sum-t)/2,最后能够得出0的数目,这样子依据0,1,2的数目再对数组进行设置值。

代码实现

算法实现类

public class Solution {
public void sortColors(int[] A) { if (A == null) {
return;
} int count = 0; // 统计1的个数
int sum = 0; // 统计数组的和 for (int i : A) {
if (i == 1) {
count++;
} sum += i;
} sum = (sum - count) /2; // 计算2的数目 count = A.length - count - sum; // 1開始出现的位置 sum = A.length - sum; // 2開始出现的位置 for (int i = 0; i < count; i++) {
A[i] = 0;
} for (int i = count; i < sum; i++) {
A[i] = 1;
} for (int i = sum; i < A.length; i++) {
A[i] = 2;
}
}
}

评測结果

  点击图片。鼠标不释放,拖动一段位置,释放后在新的窗体中查看完整图片。

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47142945

最新文章

  1. Android BLE 蓝牙编程(二)
  2. Ubuntu 下,修改 Mac address
  3. python中的IO多路复用
  4. android环境配置
  5. 设计模式学习之桥接模式(Bridge,结构型模式)(15)
  6. Dynamic CRM 2013学习笔记(三十一)自定义用excel批量导入实体数据
  7. animation of android (4)
  8. fastjson生成和解析json数据
  9. javaShop的一些总结
  10. java.lang.NoSuchFieldError: RAW_XML_FILE_HEADER,调用XWPFTemplate动态合并生成一个新的docx文档时报错
  11. Madifest文件详解
  12. js移动端横竖屏检测
  13. 【Android Widget】FragmentTabHost
  14. [深度学习]实现一个博弈型的AI,从五子棋开始(2)
  15. 提交到svn服务器时,一直缓冲不,
  16. 基于jwt的用户登录认证
  17. MVC系统过滤器 OutputCacheAttribute
  18. restTemplate.postForObject上传文件中文乱码(???.xls)
  19. Mac Maven配置
  20. c#之课后习题

热门文章

  1. Problem A: 逆序输出数列
  2. Xcode9出现错误safe area layout guide before ios 9 真正解决办法
  3. Web安全测试指南--认证
  4. Apache 优化配置10条建议
  5. Matlab横坐标从特定值开始
  6. Android Context作为参数传递this
  7. Express极简实例
  8. BOOM -- 智能合约编程
  9. Asp.net Core CORS(跨域资源共享)实验
  10. jquery元素节点操作