Leetcode-927 Three Equal Parts(三等分)
1 class Solution 2 { 3 private: 4 vector<int> result; 5 public: 6 vector<int> threeEqualParts(vector<int>& A) 7 { 8 int oneSum = 0; 9 for(auto d:A) 10 { 11 if(d==1) 12 oneSum ++; 13 } 14 15 if(oneSum==0) 16 { 17 result.push_back(0); 18 result.push_back(A.size()-1); 19 return result; 20 } 21 22 if(oneSum % 3 != 0) 23 { 24 result.push_back(-1); 25 result.push_back(-1); 26 return result; 27 } 28 29 int tmpOneSum = 0; 30 int i; 31 for(i = A.size()-1; i >= 0; i --) 32 { 33 if(A[i]==1) 34 tmpOneSum ++; 35 if(tmpOneSum == oneSum/3) 36 { 37 break; 38 } 39 } 40 41 vector<int> part3; 42 for(; i < A.size(); i ++) 43 part3.push_back(A[i]); 44 45 for(i = 0; A[i]==0; i ++) 46 ; 47 int part3End = 0; 48 49 for(int j = i; i-j < part3.size(); i ++) 50 { 51 if(A[i]!=part3[part3End++]) 52 { 53 result.push_back(-1); 54 result.push_back(-1); 55 return result; 56 } 57 } 58 59 int resultPart = i-1; 60 for(; A[i]==0; i ++) 61 ; 62 63 part3End = 0; 64 for(int j = i; i-j < part3.size(); i ++) 65 { 66 if(A[i]!=part3[part3End++]) 67 { 68 result.push_back(-1); 69 result.push_back(-1); 70 return result; 71 } 72 } 73 74 result.push_back(resultPart); 75 result.push_back(i); 76 77 return result; 78 } 79 };