leetcode-15.三数之和;53.最大子数组和;121. 买卖股票的最佳时机

47 阅读1分钟

15.三数之和

  1. 由于不能重复下标的数字,所以需要去重

  2. 首先对数组进行排序

    • a)判断是否当前的数>0,为真直接break,后面的数加上一定不为0;
    • b)设置左右指针,left = i + 1, right = nums.length - 1;
    • c)判断nums[i] + nums[left] + nums[right]的和,<0,证明数字太小,left++往后找;>0,证明数字太大,right--往前找;=0,那就是push到二维数组里;
    • d)此时nums[i]不动,判断right和left:
    nums[right] === nums[right - 1]    right--;
    nums[left] === nums[left + 1]    left++;
    

    然后再left++; right--; 寻找下一种搭配,直到left < right;

    • e)执行最外层循环;
var threeSum = function(nums) {
    nums.sort((a, b) => a - b);
    let arr = [];
    for(let i = 0; i < nums.length; i++){
        if(nums[i] > 0){
            break;
        }
        if(i > 0 && nums[i] === nums[i - 1]){
            continue;
        }
        let left = i + 1, right = nums.length - 1;
        while(right > left){
            if(nums[i] + nums[left] + nums[right] > 0){
                right--;
            }else if(nums[i] + nums[left] + nums[right] < 0){
                left++;
            }else{
                arr.push([nums[i], nums[left], nums[right]]);
                while(left < right && nums[right] === nums[right - 1]) right--;
                while(left < right && nums[left] === nums[left + 1]) left++;
                left++;
                right--;
            }
        }
    }
    return arr;
};

53.最大子数组和

要点:贪心算法

核心代码:sum = Math.max(sum + nums[i], nums[i]); 如果当前值与前边的sum累加后还不如自身大, 那就把前边的都丢掉,从自己开始累加

var maxSubArray = function(nums) {
    let maxSum = nums[0];
    let sum = 0;
    for(let i = 0; i < nums.length; i++){
        sum = Math.max(sum + nums[i], nums[i]);
        maxSum = Math.max(sum, maxSum);
    }
    return maxSum;
};

121. 买卖股票的最佳时机

方法一:暴力解法,会超时

var maxProfit = function(prices) {
    let maxProfit = 0;
    for(let i = 0; i < prices.length; i++){
        for(let j = i + 1; j < prices.length; j++){
            maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
        }
    }
    return maxProfit;
};

方法二:一次遍历

var maxProfit = function(prices) {
    let minPrice = prices[0];
    let maxProfit = 0;
    for(let i = 0; i < prices.length; i++){
        minPrice = Math.min(minPrice, prices[i]);
        maxProfit = Math.max(maxProfit, prices[i] - minPrice);
    }
    return maxProfit;
};