53. Maximum Subarray
题目:求最大子序列和
思路:动态规划——n为连续项之和,如果n<0,将n令为0,即前几项之和小于零,重新开始计算。
public class Solution {
public int maxSubArray(int[] nums) {
int ret = nums[0], n = 0;
for(int x : nums){
n +=x;
if(n > ret){
ret = n;
}
if(n < 0){
n = 0;
}
}
return ret;
}
}
152. Maximum Product Subarray
题目:求最小子序列的最大积
思路:动态规划——用max和min记录当前最大值和最小值,实际就是找到max*当前数,min*当前数以及当前数三个数的最大值和最小值。
public class Solution {
public int maxProduct(int[] nums) {
int max = nums[0], min = nums[0], ret = nums[0];
for(int i = 1; i < nums.length; i++){
int temp = max;
max = Math.max(Math.max(max*nums[i], min*nums[i]), nums[i]);
min = Math.min(Math.min(temp*nums[i], min*nums[i]), nums[i]);
ret = Math.max(ret, max);
}
return ret;
}
}
238. Product of Array Except Self
题目:返回除了自己以外所有元素的积,不允许使用多余空间
思路:算出所有不为零的数之积,并统计零的个数,然后分类讨论。O(n)
public class Solution {
public int[] productExceptSelf(int[] nums) {
int p = 1, count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0){
count++;
continue;
}
p *=nums[i];
}
for(int i = 0; i < nums.length; i++){
int temp = nums[i];
if(nums[i] == 0){
nums[i] = count>1?0:p;
}
else{
nums[i] = count>0?0:p/nums[i];
}
}
return nums;
}
}
题目要求不用除法,没看着。
另一种方法,建一个数组,将第i位放前i-1的乘积,然后反过来,计算每一项缺少的部分(其实就是它的后几项)。
public class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}