数组-(Zero Sum Subarray)返回数组中和为某个数的子串数组

'''
Given an integer array, find a subarray where the sum of numbers is zero.
Your code should return the index of the first number and the index of the last number.

Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

Note
There is at least one subarray that it's sum equals to zero.
'''

'''
# 1 两个for循环穷举
class Solution:
    def call(self, arr, sum_obj_elem, once=True):
        size = len(arr)
        result = []
        for i1 in range(size):
            tp = sum_obj_elem
            for i2 in range(i1, size):
                tp -= arr[i2]
                if tp == 0:
                    print(i1, i2)
                    result.append([i1, i2])
                    if once:
                        return result
        return result


s = Solution()
print(s.call([-3, 1, 2, -3, 4], 0, False))
'''


# 分奇偶对讨论,奇:按中轴划分-3, 1, 2。偶:按左右划分1, 6, 2, -1, -2, -6
# 一句话总结:xxxxx子串和为0,只存在奇/偶两个个数情况,所有列举两种情况时从中间展开计算和是否为零即可(奇:1 1 1, 2, -1 -1 -3;偶:1 2 , -1 -2)
class Solution2:
    def call(self, arr, sum_obj_elem, once=True):
        size = len(arr)
        result = []
        # 计算奇数形式
        for center in range(size):
            if once and len(result) > 0:
                break
            left_len = center
            right_len = size - 1 - center
            # print(left_len, right_len)
            sum = 0
            left = center
            right = center
            if left_len < right_len:
                d = left_len
            else:
                d = right_len
            sum += arr[center]
            while d > 0 and left - 1 > 0 and right + 1 < size:
                d -= 1
                left -= 1
                right += 1
                sum += arr[left]
                sum += arr[right]
                if sum == 0:
                    result.append(arr[left:right + 1])
                    break
        #  计算双数形式1,1,-1,-1
        for center in range(size - 1):
            if once and len(result) > 0:
                break
            left_len = center + 1
            right_len = size - 1 - center
            d = min(left_len, right_len)
            left = center
            right = center + 1
            # print([left], [right])
            sum = 0
            while d > 0 and left >= 0 and right < size:
                d -= 1
                sum += arr[left]
                sum += arr[right]
                if sum == 0:
                    result.append(arr[left:right + 1])
                    break
                left -= 1
                right += 1

        return result


s = Solution2()
print(s.call([5, -3, 1, 2, -3, 4, 1, 6, 2, -1, -2, -6], 0, False))

#[[-3, 1, 2], [1, 2, -3], [1, 6, 2, -1, -2, -6]]

 

posted @ 2019-03-01 17:40  jj千寻  阅读(149)  评论(0编辑  收藏  举报