75. leetcode Sort Colors
来源:互联网 发布:linux复制文件和文件夹 编辑:程序博客网 时间:2024/06/08 16:17
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.
java
class Solution { public void sortColors(int[] nums) { if (nums == null || nums.length == 0 || nums.length == 1) { return; } int left = 0; int right = nums.length - 1; int i = 0; while (i <= right && left <= right) { if (nums[i] == 1) { i++; } else if (nums[i] == 0) { swap(nums, i, left); i++; left++; } else { swap(nums, i, right); right--; } } } private void swap(int[] nums, int start, int end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; }}
python
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if nums is None or len(nums) == 0 or len(nums) == 1: return left, right, i = 0, len(nums) - 1, 0 while i <= right: if nums[i] == 1: i += 1 elif nums[i] == 0: nums[i], nums[left] = nums[left], nums[i] i, left = i + 1, left + 1 else: nums[i], nums[right] = nums[right], nums[i] right -= 1
阅读全文
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
- 75. Sort Colors LeetCode
- 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-75.Sort Colors
- 美酒问题 + 木桶倒水问题(当当网编程题)
- 调度器
- u-boot 添加设置网卡地址的命令
- 我的嵌入式5年 VS 我被国嵌的视频坑了的日子
- 异常----体系
- 75. leetcode Sort Colors
- MHA+MYSQL+KEEPALIVED实现数据库的高可用
- [2017.10.19]作业03(c)
- Python Celery 实现异步任务
- ConcurrentHashMap和HashMap的containsKey方法区别
- sql查询语句没有结果时赋值为0
- Codeforces 459E 图上DP 解题报告
- Cg Programming/Unity/Two-Sided Surfaces双面表面
- Angular(1.5)简介,引入,表达式