【leetcode】927. Three Equal Parts

題目以下:數組

Given an array A of 0s and 1s, divide the array into 3 non-empty parts such that all of these parts represent the same binary value.ide

If it is possible, return any [i, j] with i+1 < j, such that:spa

  • A[0], A[1], ..., A[i] is the first part;
  • A[i+1], A[i+2], ..., A[j-1] is the second part, and
  • A[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].code

Note that the entire part is used when considering what binary value it represents.  For example, [1,1,0] represents 6 in decimal, not 3.  Also, leading zeros are allowed, so [0,1,1]and [1,1] represent the same value.blog

 

Example 1:three

Input: [1,0,1,0,1]
Output: [0,3] 

Example 2:ci

Input: [1,1,0,1,1]
Output: [-1,-1]

 

Note:字符串

  1. 3 <= A.length <= 30000
  2. A[i] == 0 or A[i] == 1

解題思路:能夠確定的一點是A中1的個數(記爲count_1)必定是3的倍數,若是不是那麼是沒法分紅相同的三等份的;若是能夠等分,那麼每一份的1的個數count_1/3,假設每一份的有效字符串是S(有效字符串能夠理解成不包括前面的0),A就能夠表示成 0...0S0...0S0...0S 的形式。接下來倒序遍歷A,遍歷過程當中記錄1的數量,每當數量到達count_1/3的時候將這一段記爲其中一等份,那麼A就能夠分紅 [S0...0,S0...0,S]的形式,記爲parts數組,第一個S前的0是無效的,因此不須要處理。接下來就只要判斷parts數組中最後一個元素是不是前兩個元素的前綴,若是是的話,就表示能夠被等分了。最後是求等分的下標位置,只要把[S0...0,S0...0,S] 中S後面的0都給下一個元素變成[S,0...0S,0...0S]就能夠垂手可得的獲得結果了。input

代碼以下:it

class Solution(object):
    def threeEqualParts(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        A = [str(i) for i in A]
        count_1 = A.count('1')
        if count_1 == 0 :
            return [0,2]
        elif count_1 == 0 or count_1 % 3 != 0:
            return [-1,-1]

        parts = ['','','']
        times = 0
        inx = 2
        subs = ''
        for i,v in enumerate(A[::-1]):
            if v == '1':
                times += 1
            subs = v + subs
            if times == (count_1 / 3):
                parts[inx] = subs
                inx -= 1
                times = 0
                subs = ''
        #print parts
        if parts[0].startswith(parts[2]) and parts[1].startswith(parts[2]):
            second_len = len(parts[2]) + (len(parts[1]) - len(parts[2]))
            first_len = len(parts[2]) + len(parts[1]) +  + (len(parts[0]) - len(parts[2]))
            return [len(A) - first_len-1,len(A) - second_len]
            #pass
        #print parts
        return [-1,-1]
相關文章
相關標籤/搜索