[LeetCode数组划分] | 刷题打卡

572

[LeetCode数组划分] | 刷题打卡

建议读者从第1篇开始阅读,这样才能慢慢建立双指针思想,逐步过渡到双指针应用、三指针、划分思想上面来。

一直有刷题习惯,最近才看到掘金举办了刷题活动,特来参加!此题为第13题。不得不说掘金的主题就是漂亮呀!赞。

本文正在参与掘金团队号上线活动,点击 查看大厂春招职位

一、题目描述:

数组划分

描述

给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:

  • 所有小于k的元素移到左边
  • 所有大于等于k的元素移到右边

返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k。 你应该真正的划分数组 nums,而不仅仅只是计算比 k 小的整数数,如果数组 nums 中的所有元素都比 k 小,则返回 nums.length。

样例

例1:

输入:
[],9
输出:
0

例2:

输入:
[3,2,2,1],2
输出:1
解释:
真实的数组为[1,2,2,3].所以返回 1

挑战
使用 O(n) 的时间复杂度在数组上进行划分。

二、思路分析:

方法描述时间复杂度空间复杂度
双指针法快速选择,相向双指针O(N)O(N)O(1)O(1)

伪代码思路如下:

  • left = 0right = length-1
  • nums[left] < k时,left指针向右移动。
  • nums[right] >= k时,right指针向左移动。
    • 如果left <= right,交换两个值。
    • 如果left > right,返回left作为最终结果,否则返回第二步。

三、AC 代码:

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
        // back conditions
        if (nums == null) {
            return 0;
        }

        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            while (left <= right && nums[left] < k) {
                left++;
            }

            while (left <= right && nums[right] >= k) {
                right--;
            }

            if (left <= right) {
                // swap left and right
                int temp = nums[right];
                nums[right] = nums[left];
                nums[left] = temp;
                left++;
                right--;
            }
        }
        return left;
    }
}

四、总结:

这已经是第13道双指针问题了,表面上看是双指针即相向双指针,其实已经可以直接归为划分思想类的问题了。

划分思想非常重要,常用于第11、第12、第13这几类双指针问题,也用于缩减问题规模类的问题,如快速排序。

我会在第14题用快速排序对划分思想做一个详细总结。