#31 Partition Array
来源:互联网 发布:好用的看图软件 知乎 编辑:程序博客网 时间:2024/05/16 15:53
题目描述:
Given an array nums
of integers and an int k
, partition the array (i.e move the elements in "nums") such that:
- All elements < k are moved to the left
- All elements >= k are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k.
Notice
You should do really partition in array nums instead of just counting the numbers of integers smaller than k.
If all elements in nums are smaller than k, then return nums.length
Example
If nums = [3,2,2,1]
and k=2
, a valid answer is 1
.
Challenge
题目思路:Can you partition the array in-place and in O(n)?
这题也可以用two pointers的想法,l和r指针一个在头,一个在尾,i从0....r遍历,如果nums[i] < k,就l和i上的值交换;反之,则让r和i上的值交换。这里要注意的是,r换给i的值可能是个< k的东西,这种情况下,需要再和l换一次。
Mycode(AC = 13ms):
class Solution {public: int partitionArray(vector<int> &nums, int k) { // write your code here if (nums.size() == 0) return 0; int l = 0, r = nums.size() - 1; for (int i = 0; i <= r; i++) { // swap left and index if nums[i] < k if (nums[i] < k) { swap(nums, i, l); l++; } // swap right and index if nums[i] < k else { swap(nums, i, r); // it is possible that the original // nums[r] is smaller than k, in that // case, should do another swap between // l and old i if (nums[i] < k) i--; r--; } } return l; } void swap(vector<int> &nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }};
0 0
- #31 Partition Array
- Partition Array
- Partition Array
- Partition Array
- Partition Array/ Sort Color
- lintcode:Partition Array
- [刷题]Partition Array
- lintcode:Partition Array
- Balanced Partition of Array
- Partition Array的总结
- LintCode Partition Array
- Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- 561. Array Partition I
- Array Partition I
- android WebView拦截请求详解
- 玩转AppBarLayout,更酷炫的顶部栏
- 学Android开发 这19个开发工具助你顺风顺水
- 亿方云去广告v1.0官方正式版
- cc2541软件延时函数
- #31 Partition Array
- bzoj[SCOI2005]最大子矩阵
- Git基本命令使用
- 项目上线流程
- sg-uap数据库连接登录
- 使用开源项目开发vcenter客户端
- ConcurrentHashMap
- Git SSH Key 生成步骤
- UVA 1336 Fixing the Great Wall