【精】领扣LintCode算法问题答案:1854. 数组划分III

    科技2022-08-05  100

    1854. 数组划分III

    描述

    给你一个整数数组和一个整数K,请你判断数组是否可以划分为若干大小为k序列,并满足以下条件:

    数组中的每一个数恰恰出现在一个序列中一个序列中的数都是互不相同的数组中相同元素是被划分到不同序列中的

    如果可以划分,返回True,否则返回False。

    数组长度小于等于105

    样例 1:

    input: array=[1,2,3,4], k = 2 output: true

    样例 2:

    input: array=[1,2,2,3], k = 3 output: false

    原题传送门


    文章目录

    1854. 数组划分III描述样例 1:样例 2: 分析题解最后说两句声明


    分析

    这道题描述的不够通俗易懂,根据题意,分析如下 1.首先数可以被均分,即,数组长度可以整除k 2.一组当中不能有重复,即,一个数字的重复数量有限制,不能超过组的数量

    题解

    public class Solution { /** * @param array: the input array * @param k: the sequence length * @return: if it is possible, return true, otherwise false */ public boolean partitionArratIII(int[] array, int k) { // write your code here // 不够分 if (array == null || array.length < k || k < 1) { return false; } // 不能均分 if (array.length % k != 0) { return false; } // 由于一组当中不能重复,所以分成大小为k的话,每个数的最大数量就是如下,即,组的数量 int maxCount = array.length / k; Map<Integer, Integer> counter = new HashMap<>(); for (int n : array) { Integer count = counter.get(n); if (count == null) { count = 0; } if (count > maxCount) { return false; } counter.put(n, count + 1); } return true; } }

    最后说两句

    非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~

    作者水平有限,如果文章内容有不准确的地方,请指正。

    希望小伙伴们都能每天进步一点点。

    声明

    本文由二当家的白帽子博客原创,转载请注明来源,谢谢~

    Processed: 0.018, SQL: 8