LeetCode 之 Sort Colors — C 实现
来源:互联网 发布:淘宝店铺注册单安全吗 编辑:程序博客网 时间:2024/05/14 13:48
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.
Note:
You are not suppose to use the library's sort function for this problem.
这里我们分别用0,1,2 代表红、白、蓝三种颜色。
说明:不能使用库排序函数。
分析:
使用两个游标 left 和 right,left 左边为 0,right 右边为 2,它们中间为 1。
从数组开头开始扫描,遇见0就将其换到 left 左边,此处设为1,遇到1不处理继续查找,遇到 2,从数组尾部开始扫描直到找到不是 2的数字,将其对换但不改变此处的位置等待下个循环处理,只需要改变从数组后面向前扫描的指针,直到前后扫描的下标重合为止。
void sortColors(int* nums, int numsSize) { int left = 0, right = numsSize - 1;/*left指向1的位置,左边是0,right右边是2,中间是1*/ int low = 0, high = numsSize - 1; if(!nums || numsSize == 0) /*空*/ { return; } while(low <= high) { if(nums[low] == 0) { if(low > left)/* 0前面有1 */ { nums[left++] = 0; nums[low] = 1; while(left < low && nums[left] == 0)/* left移到第一个为1或者low的位置*/ { ++left; } ++low; /*移到下一个数*/ } else { ++low; ++left; } } else if(nums[low] == 1) { ++low; } else { while(low < high && nums[high] == 2)/*找第一个不是2的数*/ { --high; } nums[low] = nums[high]; /*将此处的值放入前面为2的位置*/ nums[high--] = 2; } }}
0 0
- LeetCode 之 Sort Colors — C 实现
- LeetCode之Sort Colors
- LeetCode之Sort Colors
- leetcode之Sort Colors
- LeetCode 之 Sort Colors
- 【Leetcode】之Sort Colors
- Sort Colors —LeetCode
- [leetcode-75]Sort Colors(C)
- 【C++】【LeetCode】75. Sort Colors
- leetcode Sort Colors java实现
- Leetcode之Sort Colors 问题
- LeetCode 之 Sort List — C 实现
- LeetCode —— Sort Colors
- LeetCode——Sort Colors
- LeetCode——Sort Colors
- LeetCode刷题(C++)——Sort Colors(Medium)
- [C语言][LeetCode][75]Sort Colors
- Sort Colors —1—Leetcode
- Leetcode[104]-Maximum Depth of Binary Tree
- "The method findViewById(int) is undefined for ..."
- 构建素数表
- 转加解密算法的一些概述总结
- Android开发之如何保证Service不被杀掉(broadcast+system/app)
- LeetCode 之 Sort Colors — C 实现
- php+jquery+ajax+json简单小例子
- 将图片转换为NSData
- 2015 辽宁省赛C题 dp+单调队列优化
- poj2559
- Openstack中为虚拟机使用CDROM光驱设备
- PHP函数:var_export()
- Spring Data Jpa简单入门
- php键值互换时走的一个弯路