zoukankan      html  css  js  c++  java
  • leetcode DP

    DP divide and approach分而治之

    题号:53. Maximum Subarray

    Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
    
    For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
    the contiguous subarray [4,-1,2,1] has the largest sum = 6.

    Apparently, this is a optimization problem, which can be usually solved by DP. So when it comes to DP, the first thing for us to figure out is the format of the sub problem(or the state of each sub problem). The format of the sub problem can be helpful when we are trying to come up with the recursive relation.

    divide into small problem:  maxSubArray(int A[], int i), which means the maxSubArray for A[0:i ] which must has A[i] as the end element.

    python

    class Solution(object):
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            dp = [0]*len(nums)
            dp[0] = nums[0]
            max_num = nums[0]
            for i in range(1,len(nums)):
                dp[i] = nums[i] + (dp[i-1] if dp[i-1] > 0 else 0)
                max_num = max(dp[i],max_num)
            return max_num

    java

    public int maxSubArray(int[] A) {
            int n = A.length;
            int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
            dp[0] = A[0];
            int max = dp[0];
            
            for(int i = 1; i < n; i++){
                dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
                max = Math.max(max, dp[i]);
            }
            
            return max;
    }

    其他答案:

    python

    class Solution:
        # @param A, a list of integers
        # @return an integer
        # 6:57
        def maxSubArray(self, A):
            if not A:
                return 0
    
            curSum = maxSum = A[0]
            for num in A[1:]:
                curSum = max(num, curSum + num)
                maxSum = max(maxSum, curSum)
    
            return maxSum

    java

    public static int maxSubArray(int[] A) {
        int maxSoFar=A[0], maxEndingHere=A[0];
        for (int i=1;i<A.length;++i){
            maxEndingHere= Math.max(maxEndingHere+A[i],A[i]);
            maxSoFar=Math.max(maxSoFar, maxEndingHere);    
        }
        return maxSoFar;
    }

     169. Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

    You may assume that the array is non-empty and the majority element always exist in the array.

    python

    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            dic = {}
            for item in nums:
                try:
                    dic[item] +=  1
                    if dic[item] > len(nums)//2:
                        return item
                except:
                    dic[item] = 1
                    if dic[item] > len(nums)//2:
                        return item

    other:

    python

    重要,记住这个可以统计list array某元素个数的方式!!!!!!!

    class Solution:
        def majorityElement(self, nums):
            majority_count = len(nums)//2
            for num in nums:
                count = sum(1 for elem in nums if elem == num)
                if count > majority_count:
                    return num
    class Solution:
        def majorityElement(self, nums):
            counts = collections.Counter(nums)
            return max(counts.keys(), key=counts.get)

    研究一下collection这个包

  • 相关阅读:
    ab Apache HTTP server benchmarking tool
    压缩JS的类
    看电影学人生:《白银帝国》有感
    JavaScript 闭包
    微软为asp.net ajax和jquery创建了CDN
    JavaScript工具
    Mysql初始化root密码和允许远程访问
    一步一步学Ruby(二十一):文件操作2
    测试包含HttpContext.Current的代码
    What’s the difference between <system.web> and <system.webServer>?
  • 原文地址:https://www.cnblogs.com/developerchen/p/7825761.html
Copyright © 2011-2022 走看看