Lintcode31 Partition Array solution题解
来源:互联网 发布:怎么才能看到淘宝直播 编辑:程序博客网 时间:2024/06/03 21:25
【题目描述】
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
给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:所有小于k的元素移到左边;所有大于等于k的元素移到右边;返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k。
注意:你应该真正的划分数组 nums,而不仅仅只是计算比 k 小的整数数,如果数组 nums 中的所有元素都比 k 小,则返回 nums.length。
【题目链接】
http://www.lintcode.com/en/problem/partition-array/
【题目解析】
容易想到的一个办法是自左向右遍历,使用right保存大于等于 k 的索引,i则为当前遍历元素的索引,总是保持i >= right, 那么最后返回的right即为所求。
自左向右遍历,遇到小于 k 的元素时即和right索引处元素交换,并自增right指向下一个元素,这样就能保证right之前的元素一定小于 k. 注意if判断条件中i >= right不能是i > right, 否则需要对特殊情况如全小于 k 时的考虑,而且即使考虑了这一特殊情况也可能存在其他 bug. 具体是什么 bug 呢?欢迎提出你的分析意见~
有了解过 Quick Sort 的做这道题自然是分分钟的事,使用左右两根指针 left,right 分别代表小于、大于等于 k 的索引,左右同时开工,直至 left>right.
大循环能正常进行的条件为 left<=right, 对于左边索引,向右搜索直到找到小于 k 的索引为止;对于右边索引,则向左搜索直到找到大于等于 k 的索引为止。注意在使用while循环时务必进行越界检查!
找到不满足条件的索引时即交换其值,并递增left, 递减right. 紧接着进行下一次循环。最后返回left即可,当nums为空时包含在left = 0之中,不必单独特殊考虑,所以应返回left而不是right.
【参考答案】
http://www.jiuzhang.com/solutions/partition-array/
- Lintcode31 Partition Array solution题解
- Lintcode96 Partition List solution题解
- Lintcode64 Merge Sorted Array solution 题解
- Leetcode题解-561. Array Partition I
- Lintcode50 Product of Array Exclude Itself solution 题解
- Lintcode62 Search in Rotated Sorted Array solution 题解
- Lintcode63 Search in Rotated Sorted Array II solution 题解
- Lintcode100 Remove Duplicates From Sorted Array solution 题解
- Lintcode101 Remove Duplicates From Sorted Array || solution 题解
- Lintcode159 Find Minimum in Rotated Sorted Array solution 题解
- Lintcode160 Find Minimum in Rotated Sorted Array II solution 题解
- Partition Array
- Partition Array
- Partition Array
- Partition index solution.
- Lintcode177 Convert Sorted Array to Binary Search Tree With Minimal Height solution 题解
- [LeetCode 86] Partition List Solution
- Lintcode13 strStr solution 题解
- 安卓开发中Theme.AppCompat.Light的解决方法
- opencv历史代码下载
- tf.contrib.rnn.BasicLSTMCell, tf.contrib.rnn.MultiRNNCell深度解析
- 第三十九章项目六 回文数
- LeetCode-445. Add Two Numbers II (JAVA)链表数字加法
- Lintcode31 Partition Array solution题解
- stl的二分函数
- 瑞神要考研(山东科技大学第四届ACM校赛)
- Robotframework--->SetUp的使用
- 计算几何摸黑(2)-点和直线
- 第六章 6-1 键盘消息
- 二叉树的中序遍历
- IMWeb训练营作业2
- Dialog的isShowing()方法一直返回为true