• 一、题目
  • 二、解题思路
  • 三、解题代码

    一、题目

    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.

    Notice

    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

    二、解题思路

    根据给定的k,也就是类似于Quick Sort中的pivot,将array从两头进行缩进,时间复杂度 O(n)

    三、解题代码

    1. public class Solution {
    2. private void swap(int i, int j, int[] arr) {
    3. int tmp = arr[i];
    4. arr[i] = arr[j];
    5. arr[j] = tmp;
    6. }
    7. /**
    8. *@param nums: The integer array you should partition
    9. *@param k: As description
    10. *return: The index after partition
    11. */
    12. public int partitionArray(int[] nums, int k) {
    13. int pl = 0;
    14. int pr = nums.length - 1;
    15. while (pl <= pr) {
    16. while (pl <= pr && nums[pl] < k) {
    17. pl++;
    18. }
    19. while (pl <= pr && nums[pr] >= k) {
    20. pr--;
    21. }
    22. if (pl <= pr) {
    23. swap(pl, pr, nums);
    24. pl++;
    25. pr--;
    26. }
    27. }
    28. return pl;
    29. }
    30. }