栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

数组中给定数字的最小窗口

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数组中给定数字的最小窗口

一个遍历列表的简单解决方案。

  1. 具有左右指针,最初都为零
  2. 向前移动右指针,直到[L..R]包含所有元素(如果右到达末尾,则退出)。
  3. 向前移动左指针,直到[L..R]不包含所有元素。查看[L-1..R]是否短于当前的最佳水平。

这显然是线性时间。您只需要跟踪子数组中B的每个元素有多少即可,以检查子数组是否是潜在的解决方案。

此算法的伪代码。

size = bestL = A.length;needed = B.length-1;found = 0; left=0; right=0;counts = {}; //counts is a map of (number, count)for(i in B) counts.put(i, 0);//Increase right boundwhile(right < size) {    if(!counts.contains(right)) continue;    amt = count.get(right);    count.set(right, amt+1);    if(amt == 0) found++;    if(found == needed) {        while(found == needed) { //Increase left bound if(counts.contains(left)) {     amt = count.get(left);     count.set(left, amt-1);     if(amt == 1) found--; } left++;        }        if(right - left + 2 >= bestL) continue;        bestL = right - left + 2;        bestRange = [left-1, right] //inclusive    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/382577.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号