首页 > 其他分享 >LWC 54:697. Degree of an Array

LWC 54:697. Degree of an Array

时间:2023-07-10 16:31:53浏览次数:39  
标签:rt lf cnt 697 nums int max LWC Array


LWC 54:697. Degree of an Array

传送门:697. Degree of an Array

Problem:

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2:

Input: [1,2,2,3,1,4,2]
Output: 6

Note:

  • nums.length will be between 1 and 50,000.
  • nums[i] will be an integer between 0 and 49,999.

思路:
可以确定,答案一定是频次出现最多的元素,在数组中的最左边界和最右边界之差。当然频次出现最多的元素可能有多个,遍历一遍这些元素即可。

代码如下:

public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> lf  = new HashMap<>();
        Map<Integer, Integer> rt  = new HashMap<>();
        Map<Integer, Integer> cnt = new HashMap<>();

        for (int i = 0; i < nums.length; ++i) {
            if (!lf.containsKey(nums[i])) lf.put(nums[i], i);
            rt.put(nums[i], i);
            cnt.put(nums[i], cnt.getOrDefault(nums[i], 0) + 1);
        }

        int degree = Collections.max(cnt.values());
        int ans = Integer.MAX_VALUE;
        for (int key : cnt.keySet()) {
            if (degree == cnt.get(key)) {
                ans = Math.min(ans, rt.get(key) - lf.get(key) + 1);
            }
        }
        return ans;
    }

尺取法

构造合法窗口,在合法窗口下更新最小长度。时间复杂度O(n)

可参考博文:
javascript:void(0)

代码如下:

public int findShortestSubArray(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int max = 0;
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        for (int key : map.keySet()) {
            max = Math.max(max, map.get(key));
        }

        int ans = 1 << 29;
        Map<Integer, Integer> cnt = new HashMap<>();
        int lf = 0, rt = 0;
        int window = 0;
        for (;;) {
            while (rt < nums.length && window != max) {
                cnt.put(nums[rt], cnt.getOrDefault(nums[rt], 0) + 1);
                window = Math.max(window, cnt.get(nums[rt]));
                rt ++;
            }
            if (window != max) break;
            ans = Math.min(ans, rt - lf);
            cnt.put(nums[lf], cnt.get(nums[lf]) - 1);
            lf ++;
            window = Collections.max(cnt.values());
        }
        return ans;
    }


标签:rt,lf,cnt,697,nums,int,max,LWC,Array
From: https://blog.51cto.com/u_16184402/6678335

相关文章

  • ArrayList 源码阅读
    ArrayList源码阅读常用的有序集合,采用的是线性结构,和ArrayList形成对比的是LinkedList,线性表的优点在于遍历查询,链表优点在于修改。属性privatestaticfinallongserialVersionUID=8683452581122892189L;/***m默认大小*/privatestaticfinalintDEFAULT_CAPA......
  • ChatGPT还是有点东西的-public static <T> List<T> Arrays.asList(T... a) {...}
    背景业务开发需要判断业务状态是否在30、40、50、60的集合内,所以写了以下代码int[]inLiq={30,40,50,60};returnArrays.asList(inLiq).contains(o.getOrderStatus());自我Review代码时,验证了下这行代码,发现状态为30时,仍然返回false。在自我怀疑中调整代码,并验证,代码如下:......
  • 2023.0705 学习记录(递归,var,foreach,Array)
    递归1.做一个累乘的递归代码:publicstaticintmultiplications(inta){if(a==1){return1;}returna*multiplications(a-1);}2.做一个1-2+3-4..递归pub......
  • JavaScript(三)Array的高阶函数
    map、reducemap:map()方法定义在JavaScript的Array中,接收一个函数对象作为参数,函数定义运算规则,对array中的每个元素进行运算,结果是一个新的array。functionpow(x){returnx*x;}vararr=[1,2,3,4,5,6,7,8,9];varresults=arr.map(pow);//[1,4,9......
  • C++面试八股文:std::array如何实现编译器排序?
    C++面试八股文:std::array如何实现编译器排序?某日二师兄参加XXX科技公司的C++工程师开发岗位第25面:面试官:array熟悉吗?二师兄:你说的是原生数组还是std::array?面试官:你觉得两者有什么区别?二师兄:区别不是很大,原生数组(非动态数组)和std::array都在栈上开辟空间,初始化的时候......
  • array_reduce的使用
    当使用array_reduce函数编写博客时,可以使用它来对一个数组进行迭代并将每个元素归约(规约)成一个单一的值。下面是一个简单的示例来说明它的用法://假设我们有一个博客数组,每个博客都有一个评论数$blogs=[['title'=>'博客1','comments'=>10],['title'=>'博客......
  • cpp: Two-level pointer and double dimensional array
    /*****************************************************************//***\fileConsoleTextFileDemoApp.cppc++14*\brief***\authorgeovindu*\dateJune2023*********************************************************************/......
  • ArrayList 的底层原理和源码分析
    tip:作为程序员一定学习编程之道,一定要对代码的编写有追求,不能实现就完事了。我们应该让自己写的代码更加优雅,即使这会费时费力。推荐:体系化学习Java(Java面试专题)文章目录一、简介二、自动扩容机制三、add方法的源码分析四、addAll方法的源码分析五、set方法的源码分析六、remove方......
  • vue列表页返回数组错误Invalid prop: type check failed for prop "data". Expected A
    一个vue列表页接收后端数组时是这样写的:this.list=response.data返回如下错误:Invalidprop:typecheckfailedforprop"data".ExpectedArray,gotObject意思是希望返回一个数组但实际得到一个对象Object,网上大多是初始化userList=[]或userList=null解决的,但......
  • 牛客练习赛112 B qsgg and Subarray
    这里介绍两种解法,贪心和二分核心:只要某一个区间和为0,则所有包含该区间的和都为0贪心根据题意是求出所有⊕和为0的子区间的个数,我们按a[i]来分类,每次求出以a[i]为末尾,区间和为0的区间个数,对于a[i]来说,要想u~i的区间和为0,则需要包含所有a[i]中位为1都有0与之对应,如果u~i的区间和......