Leetcode 75 Sort Colors
来源:互联网 发布:openwrt 软件 编辑:程序博客网 时间:2024/05/29 17:22
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.
排序的问题,我直接用了最简单的冒泡。
实际上还是有其他的方法的。
public class Solution { public void sortColors(int[] nums) { for(int i = 0; i<nums.length; i++){ for(int j = i + 1; j< nums.length; j++){ if(nums[i]>nums[j]){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } }}
比如使用bucket的方法
private static final int MAX = 3;public void sortColors(int[] nums) { int[] buckets = new int[MAX]; for(int num : nums) buckets[num]++; for(int p = 0, val = 0; val < MAX; val++) { for(int count = 0; count < buckets[val]; count++) { nums[p++] = val; } }}
// one pass in place solutionvoid sortColors(int A[], int n) { int j = 0, k = n - 1; for (int i = 0; i <= k; ++i){//只有当i当前指向的元素为1的时候才会移动 if (A[i] == 0 && i != j)//当ij不等的时候 i至少会比j多加一次 因此 i会在j的后面 swap(A[i--], A[j++]);//i保持不动 队首指针后移 else if (A[i] == 2 && i != k)//找到2 就放在最后面 swap(A[i--], A[k--]);//队尾指针前移 i保持不动 }}// one pass in place solutionvoid sortColors(int A[], int n) { int j = 0, k = n-1; for (int i=0; i <= k; i++) { if (A[i] == 0) swap(A[i], A[j++]); else if (A[i] == 2) swap(A[i--], A[k--]); }}
题外话,好久不刷题,被炼狱级别的workload吓疯了。
我总是处于各种焦虑的状态,担心着很久很久以后的事情。
似乎我们从一生下来就被赶着走,没人问你开不开心,只关心你够不够达到人们觉得的“优秀”。
我不知道自己是不是真的开心。
我走得一帆风顺,似乎是,又似乎不是自己想要的东西。
希望能坚持吧。
0 0
- Leetcode 75 Sort Colors
- LeetCode 75 Sort Colors
- [leetcode 75] Sort Colors
- LeetCode 75 Sort Colors
- leetcode-75 Sort Colors
- [leetCode 75] Sort Colors
- LeetCode 75 Sort Colors
- leetcode || 75、Sort Colors
- Leetcode 75Sort Colors
- Sort Colors - LeetCode 75
- leetcode 75:Sort Colors
- LeetCode(75) Sort Colors
- Leetcode # 75 Sort Colors
- leetcode 75: Sort Colors
- Leetcode#75||Sort Colors
- Leetcode 75:Sort Colors
- 【leetcode】【75】Sort Colors
- leetcode 75:Sort Colors
- windows和linux之间的文件传输
- 按键控制数码管
- 无限分类---重新排序
- 第二学:logcat---android当中logger驱动程序的源码分析
- 关于在Linux下使用tftp的一些心得
- Leetcode 75 Sort Colors
- 被忽略的注释
- Android核心技术之(8)---四大应用组件之BroadcastReceiver
- express 4.14.1版本 npm版本3.10.10版本下 没有layout.js文件的解决方法 页面布局设置的方法
- 欢迎使用CSDN-markdown编辑器
- Codeforces 768A Oath of the Night's Watch
- 深度学习笔记二基于tensorflow的MNIST学习
- Jenkins自动部署Tomcat项目
- Beam 超实用examples之Pi值计算