problem: https://leetcode.com/problems/three-equal-parts/
首先,检测有多少个1,记作x,看是不是3的倍数。不是则说明不存在对应划分。
之后,检测末尾的0,作为每个二进制数末尾的0个数,记作y。
最后,检测是否存在3个连续、不相交的,总共包含 1/3 * x 个1,末尾有 y 个0的相等字符串(去除前导0),如果存在,就返回答案。
class Solution { public: vector<int> threeEqualParts(vector<int>& A) { vector<int> res; int nums = 0; int n = A.size(); int zeros = 0; for(int i = n - 1; i >= 0;i--) { if(A[i] == 1) break; zeros++; } for(int i = 0;i < n;i++) { if(A[i] == 1) nums++; } if(nums == 0) { return {0, n - 1}; } if(nums % 3) return {-1, -1}; int count = nums / 3; string target; int i = 0; for(int k = 0; k < 3;k++) { string str; int one_nums = 0; int zero_nums = 0; for(;i < n; i++) { if(one_nums == count && zero_nums == zeros) break; if(A[i] == 0) { if(one_nums == count) { zero_nums++; } if(!str.empty()) str.push_back(A[i]); } else if(A[i] == 1) { if(one_nums == count) { return {-1, -1}; } one_nums++; str.push_back(A[i]); } } if(target.empty()) { target = str; } else { if(target != str) return {-1, -1}; } if(k == 0) res.push_back(i - 1); else if(k == 1) res.push_back(i); } return res; } };
[贪心] leetcode 927 Three Equal Parts
原文:https://www.cnblogs.com/fish1996/p/11366538.html