美文网首页
915. 分割数组(难度:中等)

915. 分割数组(难度:中等)

作者: 一直流浪 | 来源:发表于2022-12-18 10:56 被阅读0次

题目链接:https://leetcode.cn/problems/partition-array-into-disjoint-intervals/

题目描述:

给定一个数组 nums ,将其划分为两个连续子数组 leftright, 使得:

  • left 中的每个元素都小于或等于 right 中的每个元素。
  • leftright 都是非空的。
  • left 的长度要尽可能小。

在完成这样的分组后返回 left长度

用例可以保证存在这样的划分方法。

示例 1:

输入:nums = [5,0,3,8,6]
输出:3
解释:left = [5,0,3],right = [8,6]

示例 2:

输入:nums = [1,1,1,0,6,12]
输出:4
解释:left = [1,1,1,0],right = [6,12]

提示:

  • 2 <= nums.length <= 105
  • 0 <= nums[i] <= 106
  • 可以保证至少有一种方法能够按题目所描述的那样对 nums 进行划分。

解法一:小根堆(超时未通过)

使用小根堆来记录右边元素,目的是能快速得到最小值。依次取出一个元素放入左边,然后使用左边的最大值和右边小根堆堆顶元素(最小值)比较,判断是否满足条件。

但是,当数据量很大的时候,小跟堆的效率太低,超时了,仅供参考。

class Solution {
    public int partitionDisjoint(int[] nums) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int i = 1; i < nums.length; i++) {
            queue.offer(nums[i]);
        }
        int result = 1;
        int max = nums[0];
        if (max <= queue.peek()) {
            return result;
        }
        for (int i = 1; i < nums.length; i++) {
            queue.remove(nums[i]);
            result++;
            max = Math.max(nums[i], max);
            if (max <= queue.peek()) {
                return result;
            }
        }
        return result;
    }
}

解法二:两次遍历

我们使用数组 temp 来记录右边元素的最小值,使用temp[i] 表示 nums[i] 到 nums[nums.length - 1] 的最小值。通过从右往左遍历一次,得到temp数组。再从左往右遍历一次,依次比较左边元素的最大值和右边元素的最小值temp[i + 1]。

代码:

class Solution {
    public int partitionDisjoint(int[] nums) {
        int[] temp = new int[nums.length];
        temp[nums.length - 1] = nums[nums.length - 1];
        for (int i = temp.length - 2; i >= 0; i--) {
            temp[i] = Math.min(nums[i], temp[i + 1]);
        }

        int leftMax = nums[0];

        for (int i = 0; i < nums.length; i++) {
            leftMax = Math.max(leftMax, nums[i]);
            if (leftMax <= temp[i + 1]) {
                return i + 1;
            }
        }
        return nums.length - 1;
    }
}

相关文章

  • 915. 分割数组(Python)

    难度:★★★☆☆类型:数组方法:逻辑 题目 力扣链接请移步本题传送门[https://leetcode-cn.co...

  • LeetCode 18: 4sum

    标签:数组、中等难度 问题描述 Given an array nums of n integers and an ...

  • LeetCode-python 229.求众数 II

    题目链接难度:中等 类型: 数组 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ...

  • 搜索旋转排序数组

    一、leetcode 33. 搜索旋转排序数组 题目描述(题目难度,中等) 假设按照升序排序的数组在预先未知的某个...

  • leetcode每日一题 python解法 3月31日 快速排序

    难度:中等 题目内容: 给定一个整数数组 nums,将该数组升序排列。 示例 1: 输入:[5,2,3,1]输出:...

  • LeetCode-31 下一个排列

    题目:31. 下一个排列 难度:中等 分类:数组 解决方案:数组遍历 今天我们学习第31题下一个排列,这是一个中等...

  • ARTS 02(2018/11/19)

    本篇文章你将了解到如下: Algorithm Leetcode 39 组合数组 ,难度为中等 Review 未来...

  • 数组操作练习

    前提条件 数组 概要 类型:实践难度:中等 任务描述 题 1:查找数组对象中 age 大于 18 对象编写函数 f...

  • 入门算法:归并排序

    上手难度:★★☆ 算法复杂度:O(nlogn) 排序思想: 将数组采用二分法,不断的递归分割,直至分割到单个元素,...

  • 40. 数组总和2(Python)

    更多精彩内容,请关注【力扣中等题】。 题目 难度:★★★☆☆类型:数组方法:回溯法、动态规划 给定一个数组 can...

网友评论

      本文标题:915. 分割数组(难度:中等)

      本文链接:https://www.haomeiwen.com/subject/ngvctdtx.html