原题地址:http://www.lintcode.com/zh-cn/problem/partition-array/
一.目的:根据给定K值划分数组
二.思路:1)设置左右两个指针位置,分别寻找比K大和比K小的数,即不满足条件需要换位置的数字,一个左移一个右移;
2)找到需要换位置的数字,交换其位置。
三.易错点: 根据题目要求:所有小于k的元素移到左边所有大于等于k的元素移到右边,要注意大于号和小于号及等号的使用。
四.代码如下:
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){
if(nums == null || nums.length == 0){
return 0;
}
int left = 0, right = nums.length - 1;
while(left <= right){
while(left <= right && nums[left] < k){
left++;
}
while(left <= right && nums[right] >= k){
right--;
}
if(left <= right){
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
return left;
}
}