
(关注数据结构和算法,了解更多新知识)
在网上看到这样一道题,这是一道找规律的题,有的说答案是96,有的说是40,还有的说是32。

答案是40的结论是这样得出的,从第二行开始2+5+5=12,3+6+12=21,8+11+21=40,如果这样是正确的,那么第一行的结果又是怎么算的呢?很明显我更倾向于96这个答案,关于96这个答案怎么来的,我们可以看下网友的评论。





--------------下面是今天的算法题--------------
来看下今天的算法题,这题是LeetCode的第75题:颜色分类。
问题描述
来源:LeetCode第75题
难度:中等
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。必须在不使用库内置的 sort 函数的情况下解决这个问题。
示例1:
输入:nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]
示例2:
输入:nums = [2,0,1]
输出:[0,1,2]
n == nums.length
1 <= n <= 300
nums[i] 为 0、1 或 2
问题分析
这题是让把数组中的 0 都挪到前面,2 都挪到后面,1 放到中间,其实就是荷兰国旗问题,解决方式也比较简单。
我们可以使用三个指针,left指向前面需要交换的元素,right指向后面需要交换的元素,还一个index指向当前遍历的元素。
如果index指向的元素是 0 ,就和left指向的元素交换,交换完之后left要往后移一步。同理如果index指向的元素是 2 ,就和right指向的元素交换,交换完之后right要往前移一步。否则index指向的就是 1 ,不需要做任何交换。
这里要注意index指向的值和left指向的值交换之后,index是可以往后移一步的。但index和right指向的值交换之后,index是不能往后移的,因为在交换之前,right指向的值有可能是0或者是2,所以交换之后还需要再次计算。
JAVA:
public void sortColors(int[] nums) {
int left = 0;// 0的右边界
int right = nums.length - 1;// 2的左边界
int index = 0;// 指向当前数字
while (index <= right) {
if (nums[index] == 0) {
// 如果是0,就往前面移
swap(nums, left++, index++);
} else if (nums[index] == 1) {
// 如果是1,不做任何交换
index++;
} else if (nums[index] == 2) {
// 如果是2就往后面移
swap(nums, right--, index);
}
}
}
// 交换数组中的两个数字
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
C++:
public:
void sortColors(vector<int> &nums) {
int left = 0;// 0的右边界
int right = nums.size() - 1;// 2的左边界
int index = 0;// 指向当前数字
while (index <= right) {
if (nums[index] == 0) {
// 如果是0,就往前面移
swap(nums[left++], nums[index++]);
} else if (nums[index] == 1) {
// 如果是1,不做任何交换
index++;
} else if (nums[index] == 2) {
// 如果是2就往后面移
swap(nums[right--], nums[index]);
}
}
}
C:
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void sortColors(int *nums, int numsSize) {
int left = 0;// 0的右边界
int right = numsSize - 1;// 2的左边界
int index = 0;// 指向当前数字
while (index <= right) {
if (nums[index] == 0) {
// 如果是0,就往前面移
swap(&nums[left++], &nums[index++]);
} else if (nums[index] == 1) {
// 如果是1,不做任何交换
index++;
} else if (nums[index] == 2) {
// 如果是2就往后面移
swap(&nums[right--], &nums[index]);
}
}
}
Python:
def sortColors(self, nums: List[int]) -> None:
# left 是0的右边界,right是2的左边界,index是指向当前数字。
left, right, index = 0, len(nums) - 1, 0
while index <= right:
if nums[index] == 0:
# 如果是0,就往前面移
nums[left], nums[index] = nums[index], nums[left]
left += 1
index += 1
elif nums[index] == 1:
# 如果是1,不做任何交换
index += 1
elif nums[index] == 2:
# 如果是2就往后面移
nums[right], nums[index] = nums[index], nums[right]
right -= 1

笔者简介
博哥,真名:王一博,毕业十多年,《算法秘籍》作者,专注于数据结构和算法的讲解,在全球30多个算法网站中累计做题2000多道,在公众号中写算法题解800多题,对算法题有自己独特的解题思路和解题技巧,喜欢的可以给个关注,也可以下载我整理的1000多页的PDF算法文档。
2万+

被折叠的 条评论
为什么被折叠?



