是不是因為C所以看起來很長Orz
int totalFruit(int* fruits, int fruitsSize) {
// 0 -> 1 : type of fruit ++
// remove untill 1->0 then it can add new type fruit.
if (fruitsSize<=2)
return fruitsSize;
int *count= calloc (100000, sizeof(int));
int l=0, r= l+1, type=1;
count[fruits[l]]++;
int pick = 1;
while (r<fruitsSize)
{
if ((count[fruits[r]])==0 )
{
if (type <2)
type ++;
else {
while (count[fruits[l]]>0)
{
if ((count[fruits[l]]-1) ==0)
{
count[fruits[l++]]--;
break;
}
count[fruits[l++]]--;
}
}
}
if (r-l+1 > pick)
pick = r-l+1;
count[fruits[r++]]++;
}
free(count);
return pick;
}
為什麼別人的C++看起來很短呢!!!
縮一縮以後可以長這樣, 好像沒有好去哪XD!
int totalFruit(int* fruits, int fruitsSize) {
// 0 -> 1 : type of fruit ++
// remove untill 1->0 then it can add new type fruit.
if (fruitsSize<=2)
return fruitsSize;
int *count= calloc (100000, sizeof(int));
int l=0, r= l+1, type=1;
count[fruits[l]]++;
int pick = 1;
while (r<fruitsSize)
{
if (count[fruits[r++]]++ ==0)
{
if (type <2)
type ++;
else {
while (count[fruits[l]]>0)
if ((--count[fruits[l++]])==0)
break;
}
}
if (r-l> pick) // 上面的r 加了1 了!
pick = r-l;
}
// free(count);
return pick;
}
沒有留言:
張貼留言