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)
不想写。
811

被折叠的 条评论
为什么被折叠?



