【leetcode Weekly Contest 107】927. Three Equal Parts
阿新 • • 發佈:2018-12-16
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; } };