求算法?

一串首尾相连的珠子(m个),有N种颜色(N<=10),
设计一个算法,取出其中一段,要求包含所有N中颜色,并使长度最短。
并分析时间复杂度与空间复杂度。

 

JULY_V 的博客给的答案是:

ANSWER
Use a sliding window and a counting array, plus a counter which monitors the num of zero slots in counting array. When there is still zero slot(s), advance the window head, until there is no zero slot. Then shrink the window until a slot comes zero. Then one candidate segment of (window_size + 1) is achieved. Repeat this. It is O(n) algorithm since each item is swallowed and left behind only once, and either operation is in constant time.
int shortestFullcolor(int a[], int n, int m) {
  int c[m], ctr = m;
  int h=0, t=0;
  int min=n;
  while (1) {
     while (ctr > 0 && h<n) {
       if (c[a[h]] == 0) ctr --;
       c[a[h]] ++;
       h++;
     }
     if (h>=n) return min;
     while (1) {
       c[a[t]] --;
       if (c[a[t]] == 0) break;
       t++;
     }
     if (min > h-t) min = h-t;
     t++; ctr++;
  }
}

没有看懂算法的思想。再研究。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值