Partition Array
2015-11-29 16:26
357 查看
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.
Have you met this question in a real interview? Yes
Example
If nums = [3,2,2,1] and k=2, a valid answer is 1.
Note
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
Challenge
Can you partition the array in-place and in O(n)?
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.
Have you met this question in a real interview? Yes
Example
If nums = [3,2,2,1] and k=2, a valid answer is 1.
Note
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
Challenge
Can you partition the array in-place and in O(n)?
public class Solution { /** *@param nums: The integer array you should partition *@param k: As description *return: The index after partition */ public int partitionArray(int[] nums, int k) { //write your code here int i = 0, j = nums.length - 1; while (i <= j) { while (i <= j && nums[i] < k) i++; while (i <= j && nums[j] >= k) j--; if (i <= j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; i++; j--; } } return i; } }
相关文章推荐
- 短信验证码
- Android之Context、this
- HDU-计算机学院大学生程序设计竞赛(2015’11)1002 投币洗衣机(模拟)
- iOS MKMapView 地图视图
- Java 8中处理日期和时间
- 第四章 值和单位 之 WEB安全色
- Android之Context、this
- 计算器简单封装和ASP.net
- 我看Java虚拟机(4)---Javac编译器
- Android开发Service
- Maven的安装及配置
- OPEN CASCADE Multiple Variable Function
- 使用UMeditor富文本编辑器上传图片
- Android开发Service
- 1076: [SCOI2008]奖励关
- Git 基础
- 信号量、互斥锁,读写锁和条件变量的区别
- 左值和右值问题
- 257、Binary Tree Paths
- 短信--Text与PDU