6月26日算法日记

64 阅读1分钟

1.贪心算法

image-20220626150137484

思路

首先规定最大值max为数组的第一项nums[0],然后定义一个sum总和

在for循环中每次判断sum > 0,如果为真就让sum加上该数字,否则就让sum等于该数字

max就在max和sum之间取最大值,最后返回max

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

2.两数之和

image-20220626202253174

解法

1.暴力解法

思路

两层for循环,第一个for找到一个数字num1后,然后在第二层for循环中遍历数组找到num2,如果num1和num2相加等于target,那么就返回这两个数的下标。

var twoSum = function (nums, target) {
  for (let i = 0; i < nums.length; i++) {
    for(let j = i + 1; j < nums.length; j++) {
        if(nums[i] + nums[j] == target) {
            return new Array(i, j)
        }
    }
  }
};

时间复杂度为O(n²)

2.巧妙优化

思路

只需要一次for循环,每次循环得到nums[i],之后判断target - nums[i]的差值diff是否在数组中,如果存在就返回i和该值的下标

var twoSum = function (nums, target) {
  let map = new Map();
  let result = [];
  for (var i = 0; i < nums.length; i++) {
    let difference = target - nums[i];
    if (map.has(difference)) {
      result.push(map.get(difference), i);
      return result;
    } else {
      //nums[i]为map的key,i为map的value
      map.set(nums[i], i);
    }
  }
};

时间复杂度为O(n)