Given an array
A
of0
s and1
s, divide the array into 3 non-empty parts such that all of these parts represent the same binary value.If it is possible, return any
[i, j]
withi+1 < j
, such that:
A[0], A[1], ..., A[i]
is the first part;A[i+1], A[i+2], ..., A[j-1]
is the second part, andA[j], A[j+1], ..., A[A.length - 1]
is the third part.- All three parts have equal binary value.
If it is not possible, return
[-1, -1]
.Note that the entire part is used when considering what binary value it represents. For example,
[1,1,0]
represents6
in decimal, not3
. Also, leading zeros are allowed, so[0,1,1]
and[1,1]
represent the same value.
Example 1:
Input: [1,0,1,0,1] Output: [0,3]
提交后的输出和run code的总是不一样,run code结果正确,提交就不对,居然没有第一时间想到是没有初始化。
思路:将1的个数记录出来,如果不是三的倍数,肯定不存在分割方式。每个区域1的个数相同,记录最后一个区域最后一个1后面0的个数,如果三个二进制结果一样,则前两个后面的0一定一样,这样就可以将三个区域划分出来,然后从每个最后一位一位开始比较,如果到该区域第一个1这三个区域的数字都相同,则成立,否则不存在这样的划分。
class Solution {
public:
vector<int> threeEqualParts(vector<int>& A) {
int p1=0,p2=3,sum1=0,z=0;
int l=A.size();
int flag=0;
for(int i=0;i<A.size();i++)
{
if(A[i]) sum1++;
}
if(sum1%3!=0){p1=-1;p2=-1;}
else if(sum1!=0)
{
sum1=sum1/3;
for(int i=l-1;i>=0&&A[i]!=1;i--) z++;
int t=sum1;
for(int i=0;i<l;i++)
{
if(A[i]) t--;
if(!t)
{
p1=i+z;
for(i++;i<p1+1;i++)
{
if(A[i]==1)
{
flag=1;
break;
}
}
break;
}
}
t=sum1;
for(int i=p1+1;i<l;i++)
{
if(A[i]) t--;
if(!t)
{
p2=i+z+1;
for(i++;i<p2;i++)
{
if(A[i]==1)
{
flag=1;
break;
}
}
break;
}
}
// cout<<p1<<' '<<p2<<endl;
// cout<<flag<<endl;
if(flag==0)
{
int j=l-1;
int i=p2-1;
int k=p1;
for(;j>=p2&&i>p1&&k>=0;k--)
{
if(!(A[i]==A[j]&&A[i]==A[k]))
{
flag=1;
break;
}
if(A[i]) sum1--;
if(sum1==0) break;
j--;
i--;
}
}
// cout<<flag<<endl;
}
if(flag)
{
p1=-1;
p2=-1;
}
vector<int> res;
res.push_back(p1);
res.push_back(p2);
return res;
}
};