您的位置:首页 > 其它

lintcode数组划分

2018-03-12 23:40 197 查看

题目:

给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:
所有小于k的元素移到左边
所有大于等于k的元素移到右边
返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k。

样例:

给出数组 nums = 
[3,2,2,1]
 和 k = 
2
,返回 
1


思路:

从数组两头分别找大于k和小于k的数,并进行交换

答案:

private void swap(int[] nums, int x, int y){
int tmp = nums[x];
nums[x] = nums[y];
nums[y] = tmp;
}

public int partitionArray(int[] nums, int k) {
//write your code here
if(nums == null || nums.length == 0) return 0;

int start = 0, end = nums.length - 1;

while(true){
while(start < end && nums[start] < k) start++;

while(start < end && nums[end] >= k) end--;

if(start >= end) break;

swap(nums, start, end);
}

return nums[end] < k ? end + 1 : end;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: