【leetcode】数组类——子数组类题目

数组类——子数组类题目

序号 题目 难度 代码
78 Subsets medium python、java、c++
90 Subsets II medium python、java、c++
53 Maximum Subarray easy python、java、c++
152 Maximum Product Subarray medium python、java、c++
239 Sliding Window Maximum hard python、java、c++
295 Find Median from Data Stream hard python、java、c++
228 Summary Ranges medium python、java、c++
163 Missing Ranges medium python、java、c++
325 Maximum Size Subarray Sum Equals k medium python、java、c++
209 Minimum Size Subarray Sum medium python、java、c++
238 Product of Array Except Self medium python、java、c++
128 Longest Consecutive Sequence Hard python、java、c++

78. Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def dfs(nums, index, path, ans):
            ans.append(path)
            [dfs(nums, i + 1, path + [nums[i]], ans) for i in range(index, len(nums))]

        ans = []
        dfs(nums, 0, [], ans)
        return ans

80. Remove Duplicates from Sorted Array II

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if len(nums) <= 2:
            return len(nums)
        cnt = 0
        j = 1
        for i in range(1, len(nums)):
            if nums[i] == nums[i - 1]:
                cnt += 1
                if cnt < 2:
                    nums[j] = nums[i]
                    j += 1
            else:
                nums[j] = nums[i]
                j += 1
                cnt = 0
        return j

53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        presum = maxsum = nums[0]
        for i in range(1,len(nums)):
            presum = max(presum + nums[i],nums[i])
            maxsum = max(presum,maxsum)
        return maxsum

152. Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        maxdp = [0 for _ in range(0,len(nums))]
        mindp = [0 for _ in range(0,len(nums))]
        maxdp[0] = mindp[0] = nums[0]
        ans = nums[0]
        for i in range(1,len(nums)):
            maxdp[i] = max(mindp[i - 1] * nums[i], nums[i], maxdp[i - 1] * nums[i])
            mindp[i] = min(mindp[i - 1] * nums[i], nums[i], maxdp[i - 1] * nums[i])
            ans = max(maxdp[i],ans)
        return ans

239. Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the knumbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation: 
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Note: 
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        if k == 0:
            return []
        ans = [0 for _ in range(len(nums) - k + 1)]
        stack = collections.deque([])
        for i in range(0, k):
            while stack and nums[stack[-1]] < nums[i]:
                stack.pop()
            stack.append(i)
        ans[0] = nums[stack[0]]
        idx = 0
        for i in range(k, len(nums)):
            idx += 1
            if stack and stack[0] == i - k:
                stack.popleft()
            while stack and nums[stack[-1]] < nums[i]:
                stack.pop()
            stack.append(i)
            ans[idx] = nums[stack[0]]

        return ans        

295. Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

Follow up:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
class MedianFinder:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.left = []
        self.right = []
        self.median = None

    def addNum(self, num: int) -> None:
        left = self.left
        right = self.right
        if self.median is None:
            self.median = num
            return

        if num <= self.median:
            heapq.heappush(left, -num)
        else:
            heapq.heappush(right, num)

        if len(left) > len(right) + 1:
            top = -heapq.heappop(left)
            heapq.heappush(right, self.median)
            self.median = top
        if len(right) > len(left) + 1:
            top = heapq.heappop(right)
            heapq.heappush(left, -self.median)
            self.median = top

    def findMedian(self) -> float:
        left, right = self.left, self.right
        if len(left) == len(right):
            return self.median
        elif len(left) > len(right):
            return (self.median - left[0]) / 2.0
        if len(right) > len(left):
            return (self.median + right[0]) / 2.0
        
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()

228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

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.
class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        def outputrange(start,end):
            if start == end:
                return str(start)
            return '{}->{}'.format(start,end)
        if not nums:
            return []
        ans = []
        start = 0
        for i in range(0,len(nums)-1):
            if nums[i] + 1 != nums[i + 1]:
                ans.append(outputrange(nums[start],nums[i]))
                start = i + 1
        ans.append(outputrange(nums[start],nums[-1]))        
        return ans

163.missing-ranges

Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.

For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

class Solution(object):
    def findMissingRanges(self, nums, lower, upper):
        """
        :type nums: List[int]
        :type lower: int
        :type upper: int
        :rtype: List[str]
        """
        ans = []
        nums = [lower - 1] + nums + [upper + 1]
        for i in range(0, len(nums) - 1):
            if nums[i] + 2 == nums[i + 1]:
                ans.append(str(nums[i] + 1))
            if nums[i + 1] > nums[i] + 2:
                ans.append(str(nums[i] + 1) + "->" + str(nums[i + 1] - 1))
        return ans

325.maximum-size-subarray-sum-equals-k

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.

Note:The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.

Example 1:

Given nums = [1, -1, 5, -2, 3], k = 3, return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)

Example 2:

Given nums = [-2, -1, 2, 1], k = 1, return 2. (because the subarray [-1, 2] sums to 1 and is the longest)

Follow Up:Can you do it in O(n) time?

class Solution(object):
    def maxSubArrayLen(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        d = {0: -1}
        maxLen = 0
        _sum = 0
        for i in range(0, len(nums)):
            _sum += nums[i]
            if _sum not in d:
                d[_sum] = i
            if _sum - k in d:
                maxLen = max(maxLen, i - d[_sum - k])
        return maxLen

209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example: 

Input:s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray[4,3]has the minimal length under the problem constraint.

Follow up:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 

class Solution:
    def minSubArrayLen(self, s: int, nums: List[int]) -> int:
        _sum = 0
        j = 0
        ans = float('inf')
        for i in range(0,len(nums)):
            while j < len(nums) and _sum < s:
                _sum += nums[j]
                j += 1
            if _sum >= s:
                ans = min(ans,j-i)
            _sum -= nums[i]
        return ans if ans != float('inf') else 0

238. Product of Array Except Self

Given an array nums of n integers where n > 1,  return an array outputsuch that output[i] is equal to the product of all the elements of numsexcept nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        dp = [1] * len(nums)
        for i in range(1,len(nums)):
            dp[i] = dp[i-1]*nums[i-1]
        prod = 1
        for i in reversed(range(0,len(nums))):
            dp[i] = dp[i]*prod
            prod *= nums[i]
        return dp

128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        ans = 0
        s = set(nums)       # set() 函数创建一个无序不重复元素集
        for num in nums:
            if num in s:
                s.discard(num)
                cnt = 1
                left = num - 1
                right = num + 1
            while left in s:
                s.discard(left)
                cnt += 1
                left -= 1 
            while right in s:
                s.discard(right)
                cnt += 1 
                right += 1
            ans = max(ans,cnt)
        return ans

猜你喜欢

转载自blog.csdn.net/imsuhxz/article/details/87916686
今日推荐