2022年11月22日 星期二

[1437] Check If All 1's Are at Least Length K Places Away(TBD)

寫了一個很醜的答案,然後發現其實只要幾行就好了?! (泣)
用一個 last 去存上一個1出現的index , 然後遇到下一個1 就相減求出它們的距離,
並把last 更新的現在的 1. 初始值last 設為負一,這樣也可以考慮進去開頭是0的情況. 
(開頭是0 的部份,不管它有幾個0都可以不必計入。尾巴的零也是一樣;但基本上尾巴的0可以忽略不計(?!)

有想到的話再回來寫精妙版本XD
bool kLengthApart(int* nums, int numsSize, int k){
int fixIndex=1;
int count0=0;
bool isZero = (nums[0]==0)?true:false;
if (nums[0]==0)
{
for (fixIndex=0;fixIndex<numsSize;fixIndex++)
if(nums[fixIndex]!=0)
break;
count0=0;
isZero=false;
}
for (int i=fixIndex+1;i<numsSize;i++)
{
if (isZero)
{
if(nums[i]==1)
{
isZero=false;
if (count0<k)
return false;
count0=0;
}
else
{
count0++;
continue;
}
}
else // not zero
{
if (nums[i]==1 && k>0)
return false;

if (nums[i]==0)
{
isZero=true;
count0=1;
}
}
}
return true;
}

沒有留言:

張貼留言