算法描述
给定一个数组和一个数k,划分数组,似的左边的值都小于k,右边的数大于等于k,返回划分数组的位置,例:[3, 2, 1] k = 1 --> 1, [2, 8, 3, 7] k = 9 --> 4
解题思路
参照快速排序算法,设左右两个指针,如果左边大于右边,则交换,这里需要注意边界问题,时间复杂度是O(n)
示例代码
public int partitionArray(int[] nums, int k) {
// write your code here
if (nums.length <= 0) {
return 0;
}
int low = 0, high = nums.length - 1;
while(low < high) {
while(nums[low] < k && (low < high)) {
low++;
}
while(nums[high] >= k && (low < high)) {
high--;
}
if (low < high) {
int temp = nums[low];
nums[low] = nums[high];
nums[high] = temp;
low++;
high--;
}
}
if (nums[low] >= k) {
return low;
}
return low + 1;
}
网友评论