有一個array只有0跟1, 想成是花瓶, 0表示沒花, 1表示有
相鄰的不能都插花, 必須間隔一個以上;
頭的左邊跟尾的右邊可以當做0.
給n枝花, 請回傳是放的下還是放不下~~~~
感覺是一個很有趣的題目
可是我怎麼都寫不好呢~(哭)
下面算是針對測資寫到過的概念
好像不一該貼出來啊啊啊因為實在太丟臉了啊啊啊啊啊~~~~~~
Can Place Flowers
bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n) {
int *stack = malloc(sizeof(int)*flowerbedSize);
int i,j,index=0;
if (flowerbedSize == 1 && flowerbed[0]==0)
return true;
if (flowerbedSize == 2 && flowerbed[0]==0 && flowerbed[1]==0 && n==1)
return true;
for (i=0;i<flowerbedSize;i++)
{
if (flowerbed[i] == 0)
{
stack[index++] = 0;
}
else
{
if(index==2 && stack[0]==0 && stack[1]==0)
{
index -=2;
n--;
}
while((index-3)>=0)
{
if (stack[index-2]==1)
break;
if (stack[index-3]==1)
{
index -=2;
}
else if(stack[index-3]==0 && stack[index-2]==0 && stack[index-1]==0)
{
index-=2;
n--;
}
else
break;
}
if(index==2 && stack[0]==0 && stack[1]==0)
{
index -=2;
n--;
}
stack[index++] = 1;
}
}
while((index-2)>=0)
{
if(stack[index-2]==0 && stack[index-1]==0)
{
index-=2;
n--;
}
else
break;
}
if(index==1 && stack[0]==0)
{
index -=2;
n--;
}
return (n<=0)? true:false;
}
後來覺得怎麼想都不對QQ
(因為怎麼寫都不對哈哈哈)
才發現原來用數的就可以了 QQ
我又想的太難了啊啊啊~~~(奔入雨中)
bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n) {
int i,zerocount = 1;
for (i=0;i<flowerbedSize;i++)
{
zerocount = (flowerbed[i]==0) ? (zerocount+1) :0;
if(zerocount==3)
{
zerocount=1;
n--;
}
}
if (zerocount==2)
n--;
return n<=0?(true):(false);
}
沒有留言:
張貼留言