求珠子的长度最小区间

发布时间:2020-06-27 05:54:47 作者:小止1995
来源:网络 阅读:550

有一串首尾相连的珠子,共有m个,每一个珠子有一种颜色,并且颜色的总数不超过n(n<=10),求连续的珠子的颜色总数为n时,长度最小的区间。

#include <iostream>
using namespace std;
#define MAXN 10
int colors[MAXN];//record the counter of one color
int colorsCounter;
void find(int arr[],int len, int colorsNeed)
{
    int bestStartIndex = 0;
    int bestLen = len;
    int lastStartIndex = 0;
    
    for ( int i=0; i<len; ++i) {
        if (!colors[arr[i]])
            colorsCounter++;
        colors[arr[i]]++;
        if (colorsCounter==colorsNeed) {
            int j = lastStartIndex;
            while (colors[arr[j]]>1) {
                colors[arr[j]]--;
                ++j;
            }
            if (i-j+1<bestLen) {
                bestStartIndex = j;
                bestLen = i-j+1;
                if (bestLen==colorsNeed)
                    break;
            }
            lastStartIndex = j;
        }
    }
推荐阅读:
  1. 求最小的k个数
  2. mysql求长度的函数是哪个

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

相连 首尾

上一篇:Zabbix2.4安装和问题总结(一)

下一篇:网页在线分享的几个挂件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》