Google面试题专题7 - leetcode930. Binary Subarrays With Sum/228. Summary Ranges

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/84672912

930. Binary Subarrays With Sum

题目描述

数组A仅包含0和1,有多少和为S的非空子数组。

例子

Input: A = [1,0,1,0,1], S = 2
Output: 4

Explanation:
The 4 subarrays are bolded below:
[1,0,1]
[1,0,1]
[0,1,0,1]
[1,0,1]

思想

非空子数组,起始位置为i,截止位置为j,暴力先求前缀数组和,再取差值作为A[i:j]的和,时间复杂度O(n^2)。

因为数组只包含0和1,所以可以观察出数组的前缀和是一递增序列。需要在该序列中找到两数差值为S,想到2Sum

建一个字典,记录当前不同前缀和的数量。
dic[i]表示和为i的前缀个数,sum[i]表示到i的前缀和。
若当前坐标是j,则目标是计算j之前共有多少个前缀和等于sum[j] - S,即dic[sum[j] - S]。

解法1
暴力,TLE

class Solution(object):
    def numSubarraysWithSum(self, A, S):
        """
        :type A: List[int]
        :type S: int
        :rtype: int
        """
        n = len(A)
        
        summ= [0] * (n+1)
        for i in range(1, n+1):
            summ[i] = summ[i-1] + A[i-1]
  
        cnt = 0
        for i in range(n+1):
            for j in range(i+1, n+1):
                if summ[j] - summ[i] == S:
                    cnt += 1
        return cnt

(改进)

class Solution(object):
    def numSubarraysWithSum(self, A, S):
        """
        :type A: List[int]
        :type S: int
        :rtype: int
        """
        cnt = summ = 0
        dic = {0:1}
        for num in A:
            summ += num
            if summ - S in dic:
                cnt += dic[summ-S]
            if summ in dic:
                dic[summ] += 1
            else:
                dic[summ] = 1
        return cnt   

简洁

class Solution(object):
    def numSubarraysWithSum(self, A, S):
        """
        :type A: List[int]
        :type S: int
        :rtype: int
        """
        cnt = summ = 0
        dic = {0:1}
        for num in A:
            summ += num
            cnt += dic.get(summ - S, 0)
            dic[summ] = dic.get(summ, 0) + 1
        return cnt   

228. Summary Ranges - Easy

题目描述

给定无重复的有序整数数组,将其拆成连续的范围。

例子
Example 1:

Input: [0,1,2,4,5,7]
Output: [“0->2”,“4->5”,“7”]

Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input: [0,2,3,4,6,8,9]
Output: [“0”,“2->4”,“6”,“8->9”]

Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

思想
因为数组已排好序,所以遍历一遍判断并存储结果即可。
Trick:’->’.join(map(str, p))
解法
最笨拙直接的方法

class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        if not nums:
            return []
        res = []
        temp = [nums[0], nums[0]]
        for num in nums[1:]:
            if num == temp[-1] + 1:
                temp[-1] = num
            else:
                if temp[0] == temp[1]:
                    res.append(str(temp[0]))
                else:
                    res.append('%s->%s'%(temp[0], temp[1]))
                temp = [num, num]
                
        if temp[0] == temp[1]:
            return res + [str(temp[0])]
        return res + ['%s->%s'%(temp[0], temp[1])]

简化代码:最后一起添加’->’

class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        res = []
        for num in nums:
            if res and num == res[-1][-1] + 1:
                res[-1] = [res[-1][0], num]
            else:
                res.append([num])
        return ['->'.join(map(str, p)) for p in res]

猜你喜欢

转载自blog.csdn.net/a786150017/article/details/84672912