Leetcode: 152, product of the maximum sequence; 295, the data stream median

152, a product of the maximum subsequence

Medium
Given an array of integers nums, identify a product of the maximum sequence of contiguous subsequence (which comprises at least a sequence number).

Example 1:

Input: [2,3, 2,4]
Output: 6
Explanation: subarray [2,3] maximum product 6.

Example 2:

Input: [-2,0, -1]
Output: 0
Explanation: 2 is not the result, because the [-2, -1] is not subarray.

Note:
Write your own time complexity is too high to pass, looking for information to see two solutions, dynamic programming and traversal, dynamic really really really is the most important, refueling
a more complete sound solution ideas (from users):

When the i-th element, we can get the product to the maximum possible from the sequences:

(1) nums [i] se

(2) nums [i-1] of the product of the maximum sequence that can be taken

(3) comprising nums [i-1] multiplied value most Dalian * nums [i] (the two portions are positive)

(4) comprising nums [i-1] is the minimum value multiplicative * nums [i] (the two portions are negative)

So for the i-th element, we need to record values ​​are three:

(1) the product can be taken to the maximum subsequence

(2) containing a current location of the most value by Dalian

(3) contains the current position of the minimum value of the multiplicative
recorded even by the smallest value, because there may be negative negative negative by

Original: https://blog.csdn.net/Try_my_best51540/article/details/84750798
code is read, it is clear to go again

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        temp = nums[0]
        n = len(nums)
        dp_max = [0 for i in range(n)]
        dp_min = [0 for i in range(n)]
        for i in range(n):
            if i == 0:
                dp_max[0] = nums[0]
                dp_min[0] = nums[0]
            else:
                dp_max[i] = max(max(dp_max[i-1]*nums[i],dp_min[i-1]*nums[i]),nums[i])
                dp_min[i] = min(min(dp_max[i-1]*nums[i],dp_min[i-1]*nums[i]),nums[i])
            temp = max(temp,dp_max[i])
        return temp

Solution 2:

First calculate the maximum value multiplied from left to right, right to left and then calculate the maximum value; the maximum value and then compared the two groups

还有一点要注意的是,上面说的一列负数的要求是负数之间是不存在零的,假如有零的话,就要分段考虑。


class Solution:
    def maxProduct(self, A):
        B = A[::-1]
        for i in range(1, len(A)):
            A[i] *= A[i - 1] or 1
            B[i] *= B[i - 1] or 1
        return max(max(A),max(B)) 

189, rotation of the array
given an array, the elements of the array to the right by k positions, wherein k is non-negative.

Example 1:

Input: [6, 7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotation to the right Step 1: [7,1 1,2,3,4,5,6]
rotates two steps to the right: [6,7,1,2,3,4,5]
rotation to the right step 3: [5,6,7,1,2,3 , 4]

Example 2:

Input: [-1, -100,3,99] and k = 2
Output: [3,99, -1, -100]
Explanation:
rotation to the right Step 1: [99, -1, -100,3]
to right rotation step 2: [3,99, -1, -100]

Description:

尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的原地算法。

Note: such a simple beginning is not doing right, title long learning algorithms brush road
Solution 1: write your own

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        k = k%len(nums)
        t = nums[-k:]
        nums[k:] = nums[:-k]
        nums[:k] = t

Solution 2:

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        k = k % len(nums)

        while k:
            nums.insert(0, nums.pop())
            k -= 1

295, the median of the data stream
difficulties
median is the middle number of the ordered list. If the list length is an even number, the median is the average of the two middle numbers.

E.g,

[2,3,4] median 3

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

A data structure designed to support the following two operations:

void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。

Example:

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

Advanced:

如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?

Notes; prove safety offer the same subject, sort () function can be submitted, but not by force snap, looked comment analysis, the size of the heap method, really difficult, very difficult

Solution 1: by the size of the heap, able to understand and continue to learn

class MedianFinder:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.vec = []
    
    def binary_insert(self,s,e,tgt):
        while s <= e:
            if s == e:
                if self.vec[s] >= tgt:
                    self.vec.insert(s,tgt)
                else:
                    self.vec.insert(s+1,tgt)
                return
            if e-s == 1 and (self.vec[e] > tgt and self.vec[s] < tgt):
                self.vec.insert(s+1,tgt)
                return
            
            mid = (s+e)//2
            if self.vec[mid] > tgt:
                e = mid - 1
            elif self.vec[mid] < tgt:
                s = mid + 1
                if self.vec[s] < tgt:
                    pass
                else:
                    self.vec.insert(s,tgt)
                    return
            else:
                self.vec.insert(mid,tgt)
                return
                
        return
        

        

    def addNum(self, num: int) -> None:
        if not self.vec:
            self.vec.append(num)
        elif num >= self.vec[-1]:
            self.vec.append(num)
        elif num <= self.vec[0]:
            self.vec.insert(0,num)
        else:
            self.binary_insert(0,len(self.vec)-1,num)
        

    def findMedian(self) -> float:
        n = len(self.vec)
        if n%2 == 0:
            return (self.vec[n//2] + self.vec[n//2 - 1])/2.0
        else:
            return self.vec[n//2]

Guess you like

Origin blog.csdn.net/Leia21/article/details/90578533