LeetCode Brush Question 1013. Divide the array into three equal parts

LeetCode Brush Question 1013. Divide the array into three equal parts

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Topic :
    Given an integer array A, only return if we can divide it into three equal non-empty parts true, otherwise return false. Formally, if we can find the index i+1 < jand satisfy (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])it, we can divide the array into three equal parts.
  • Example :
示例 1 :
输出:[0,2,1,-6,6,-7,9,1,2,0,1]
输出:true
解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
示例 2 :
输入:[0,2,1,-6,6,7,9,-1,2,0,1]
输出:false
示例 3 :
输入:[3,3,6,5,-2,2,5,1,-9,4]
输出:true
解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
  • Tips :
    1. 3 <= A.length <= 50000
    2. -10000 <= A[i] <= 10000
  • Code:
class Solution:
    def canThreePartsEqualSum(self, A: List[int]) -> bool:
        sum_val = sum(A)
        if sum_val % 3 != 0:
            return(False)
        temp = sum_val // 3
        i,j = 0,len(A) - 1
        left_val,right_val = 0,0
        while i < j:
            if left_val != temp:
                left_val += A[i]
                i += 1
            if right_val != temp:
                right_val += A[j]
                j -= 1
            if left_val == temp and right_val == temp:
                return(True)
        return(False)
# 执行用时 :448 ms, 在所有 Python3 提交中击败了65.72%的用户
# 内存消耗 :20.6 MB, 在所有 Python3 提交中击败了5.17%的用户
  • Algorithm description:
    First judge whether Athe sum of all elements can be divisible by 3, and return directly False; if it can be divisible, use a double pointer to traverse from the left and right ends to the middle, and find the cumulative sum of the two ends respectively, provided that the middle section can not be empty, i.e., loop condition to be met i < jwhen the third and the accumulated sum of the both ends, respectively, return True, otherwise return loop end False.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/106626848