41 - 最大子数组

4.19

(1)最开始想到的就是用很暴力的算法,从第一个数开始算。一直到最后一个,毫无疑问时间复杂度的是N^2。

但是没想到居然过了耶。

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        // write your code
        if(nums == null ){
            return 0;
        }
        if(nums.length ==1){
            return nums[0];
        }
        
        int length = nums.length;
        int max = nums[0];
        for(int i = 0; i<length; i++){
            int tmp = nums[i];
            for(int j = i+1;j < length ; j++){
                tmp += nums[j];
                if(tmp > max){
                    max =  tmp;
                }
            }
            if(tmp > max){
                max = tmp;
            }
        }
        return max;
    }
}

(2) 第二种算法,只扫描一遍,复杂度为O(N)

tmp用来记录累计和的大小,如果累计和为负数,则置零。

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        // write your code
        if(nums == null ){
            return 0;
        }
        if(nums.length ==1){
            return nums[0];
        }
        
        int length = nums.length;
        int max = nums[0];
        int tmp = 0;
        for(int i = 0; i < length; i++){
            tmp += nums[i];
            if(tmp > max){
                max = tmp;
            }
            
            else if(tmp < 0){
                tmp = 0;
            }
            
        }
        return max;
    }
}

(3)从网上学习到的分治算法,最大值要不出现在左侧,要不出现在右侧,要不跨越中点。这样可以采用递归。

时间复杂度是O(NlogN)

不想写。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值