LeetCode:. 1013 Partition Array Into Three Parts With Equal Sum (and the array is divided into three equal parts)

topic

Original title link

algorithm

  • Certainly violent algorithm times out, the array is divided into three parts, can be realized using two linear time Finger
  • Setting a first pointer i = 0 i=0 , the second pointer j = A . s i from e ( ) 1 j=A.size()-1 , the next determination condition pointer movement
  • Because the array elements have both positive and negative, so we can not compare the size of a way to determine the pointer to move, then we start directly from the results, and if there is an equal and are not 1 / 3 1/3 , we will move the pointer until it can not move up
  • Final judgment conditions, attention must be i + 1 < j i+1<j

AC codes (c ++)

class Solution {
public:
    bool canThreePartsEqualSum(vector<int>& A) {
        int i=0;
        int j=A.size()-1;
        int sum=0;
        for(int m=0;m<A.size();m++)
            sum=sum+A[m];
        if(sum%3!=0)
            return false;
        int arg=sum/3;
        int S1=A[i];
        int S3=A[j];
        while(arg!=S1&&i<A.size()-1)
        {
            i++;
            S1=S1+A[i];
        }
        while(arg!=S3&&j>0)
        {
            j--;
            S3=S3+A[j];
        }
        if(i+1<j&&S1==arg&&S3==arg)
            return true;
        return false;
    }
};
Published 68 original articles · won praise 7 · views 2857

Guess you like

Origin blog.csdn.net/wofanzheng/article/details/104310067