Hello Java.
题目描述:
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入:[2,0,2,1,1,0]
输出:[0,0,1,1,2,2]
进阶:
你能想出一个仅使用常数空间的一趟扫描算法吗?
题目链接:
https://leetcode-cn.com/problems/sort-colors/
最直接的思路:
class Solution {
public void sortColors(int[] nums) {
int red = 0;
int white = 0;
int blue = 0;
/* 遍历并统计信息 */
for (int n : nums) {
if (n == 0) red++;
else if (n == 1) white++;
else blue++;
}
int idx = 0;
/* 依次放置 */
for (int i = 0; i < red; i++) nums[idx++] = 0;
for (int i = 0; i < white; i++) nums[idx++] = 1;
for (int i = 0; i < blue; i++) nums[idx++] = 2;
}
}
进阶版的思路:
class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return;
}
int head = 0;
int tail = nums.length - 1;
int curr = 0;
while (head <= tail && curr <= tail) {
/* 当交换的curr值为0时一定排在最前 */
if (nums[curr] == 0) {
swap(nums, head++, curr++);
}
/* 当交换的curr值为2时有可能换过来的是0需要再次判断curr */
else if (nums[curr] == 2) {
swap(nums, tail--, curr);
}
else {
curr++;
}
}
}
private void swap(int[] nums, int a, int b) {
if (a == b) {
return;
}
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
}
Java中的for循环
- 传统for循环(适用于绝大多数情况)
- 借助迭代器进行循环(常见于遍历Collection对象)
- 在JDK1.5中出现的简化方式,又称for-each方式(适用于绝大多数情况,编译期间转换为传统方式,无性能问题)
for (int n : nums) ...
- 在顺序存储时,使用for循环更优;在链式存储时,使用for-each与迭代器循环更优
双指针法
- 这里的指针并不是传统意义上的指针,可以理解为两个标记,应用于多种算法题目场景
待续ヾ(=・ω・=)o