您的位置:首页 > 其它

31. 数组划分

2018-03-06 21:11 176 查看
给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:所有小于k的元素移到左边
所有大于等于k的元素移到右边
返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k。样例给出数组 nums = 
[3,2,2,1]
 和 k = 
2
,返回 
1
.
public class Solution {
/**
* @param nums: The integer array you should partition
* @param k: An integer
* @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 < nums.length && nums[i] < k) {
i++;
}
while (j >= 0 && nums[j] >= k) {
j--;
}
if (i > j) {
break;
}
if (i > nums.length) {
break;
}
if (j < 0) {
break;
}
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return i;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: