[Leetcode algorithm weekly] issue 3

Keywords: Javascript less Programming

First appeared in the WeChat public's front-end growth notes, written in 2019.11.13

background

This paper records the whole thinking process in the process of writing questions for reference. The main contents include:

  • Assumption of topic analysis
  • Write code validation
  • Consult others' solution
  • Thinking and summing up

Catalog

Easy

35. Search insertion location

Title address

Title Description

Given a sort array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns where it will be inserted sequentially.

You can assume that there are no duplicate elements in the array.

Example:

Input: [1,3,5,6], 5
 Output: 2

Input: [1,3,5,6], 2
 Output: 1

Input: [1,3,5,6], 7
 Output: 4

Input: [1,3,5,6], 0
 Output: 0

Assumption of topic analysis

This question is a little obvious. The stem of the question shows that it is a sort array, and the key point is a sort array, so it is obvious that the first reaction will be to use dichotomy to solve the problem. Also note that there are no duplicate elements in the array. So I will answer this question in two ways:

  • Violence, direct traversal
  • Dichotomy can be understood as continuous half elimination of impossibility

Write code validation

I. violence law

Code:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    if (nums.length === 0 || nums[0] > target) return 0;
    if(nums[nums.length - 1] < target) return nums.length;

    for(let i = 0; i < nums.length; i++) {
        if(nums[i] >= target) return i
    }
};

Result:

  • 62/62 cases passed (60 ms)
  • Your runtime beats 92.48 % of javascript submissions
  • Your memory usage beats 63.22 % of javascript submissions (33.8 MB)
  • Time complexity O(n)

II. Dichotomy

Code:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    if (nums.length === 0 || nums[0] > target) return 0;
    if(nums[nums.length - 1] < target) return nums.length;

    let left = 0; // Starting point
    let right = nums.length - 1; // End
    while(left < right) {
         // Zero fills the right displacement and uses bit operation to avoid overflow, which is equal to (left + right / 2) in most cases
        let i = parseInt((left + right) >>> 1) // Select left here
        if (nums[i] < target) { // Median less than target
            left = i + 1 // Exclude median left
        } else {
            right = i // Exclude median right
        }
    }
    return left
};

Result:

  • 62/62 cases passed (52 ms)
  • Your runtime beats 99.31 % of javascript submissions
  • Your memory usage beats 61.31 % of javascript submissions (33.8 MB)
  • Time complexity O(log2(n))

Consult others' solution

Basically, this problem is based on the dichotomy, so there is no other special solution.

Thinking and summing up

See sorting array, look up subscript, then you can decisively choose dichotomy.

38. number

Title address

Title Description

The number sequence is an integer sequence. The next number is obtained by the number sequence. The first five are as follows:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 is read as "one 1", that is, 11.

11 is read as "two 1s", that is, 21.

21 is read as "one 2", "one 1" ("one two", "one one one"), i.e. 1211.

Given a positive integer n (1 ≤ n ≤ 30), the nth term of the number sequence is output.

Note: integer order will be represented as a string.

Example:

Input: 1
 Output: "1"

Input: 4
 Output: "1211"

Assumption of topic analysis

This question is a bit convoluted. In fact, we can only look at the item on the right. Each time we read the item last time. In fact, the rule of number reporting is to combine the same consecutive numbers to report each number. The simplest idea is to use regular substitution directly. Of course, we can also answer from recursion and traversal. Let's take a look at them separately.

  • Regular method, replacing the same continuous number with length + number itself
  • Recursive method, continuously converted to n-1 solution
  • Ergodic method, continuously converted to n+1 solution

Write code validation

I. regular method

Code:

/**
 * @param {number} n
 * @return {string}
 */
var countAndSay = function(n) {
    let str = '1'
    for(let i = 1; i < n; i++) {
        // Match length + first digit is the reading
        str = str.replace(/(\d)\1*/g, (match) => (`${match.length}${match.charAt(0)}`))
    }
    return str
};

Result:

  • 18/18 cases passed (56 ms)
  • Your runtime beats 98.81 % of javascript submissions
  • Your memory usage beats 32.53 % of javascript submissions (35.6 MB)
  • Time complexity O(n)

II. Recursive method

Code:

/**
 * @param {number} n
 * @return {string}
 */
var countAndSay = function(n) {
    if (n === 1) return '1'
    debugger
    let str = countAndSay(n - 1)
    let item = str.charAt(0)

    let count = 0 // Counter
    let res = ''
    for(let i = 0; i < str.length; i++) {
        if(str.charAt(i) === item) {
            count++
        } else {
            res += `${count}${item}`
            item = str.charAt(i)
            count = 1
        }

        if (i === str.length - 1) { // Last bit, need to access
            res += `${count}${item}`
        }
    }
    return res
};

Result:

  • 18/18 cases passed (64 ms)
  • Your runtime beats 92.23 % of javascript submissions
  • Your memory usage beats 28.23 % of javascript submissions (35.7 MB)
  • Time complexity O(n^2)

III. ergodic method

Code:

/**
 * @param {number} n
 * @return {string}
 */
var countAndSay = function(n) {
    let str = '1'
    for(let i = 1; i < n; i++) {
        str = countEach(str)
    }
    function countEach(str) {
        let count = 0
        let res = ''
        for(let i = 0; i < str.length; i++) {
            if(i === 0 || str.charAt(i) === str.charAt(i - 1)) {
                count++
            } else {
                res += `${count}${str.charAt(i - 1)}`
                count = 1
            }
            if (i === str.length - 1) {
                res += `${count}${str.charAt(i)}`
            }
        }

        return res
    }

    return str
};

Result:

  • 18/18 cases passed (60 ms)
  • Your runtime beats 96.98 % of javascript submissions
  • Your memory usage beats 41.69 % of javascript submissions (35.5 MB)
  • Time complexity O(n^2)

Consult others' solution

Here we see a happy solution, direct dictionary method, with obvious shortcomings, but in the current situation, it is indeed the fastest.

I. regular method

Code:

/**
 * @param {number} n
 * @return {string}
 */
var countAndSay = function(n) {
    const map = {
        1:"1",
        2:"11",
        3:"21",
        4:"1211",
        5:"111221",
        6:"312211",
        7:"13112221",
        8:"1113213211",
        9:"31131211131221",
        10:"13211311123113112211",
        11:"11131221133112132113212221",
        12:"3113112221232112111312211312113211",
        13:"1321132132111213122112311311222113111221131221",
        14:"11131221131211131231121113112221121321132132211331222113112211",
        15:"311311222113111231131112132112311321322112111312211312111322212311322113212221",
        16:"132113213221133112132113311211131221121321131211132221123113112221131112311332111213211322211312113211",
        17:"11131221131211132221232112111312212321123113112221121113122113111231133221121321132132211331121321231231121113122113322113111221131221",
        18:"31131122211311123113321112131221123113112211121312211213211321322112311311222113311213212322211211131221131211132221232112111312111213111213211231131122212322211331222113112211",
        19:"1321132132211331121321231231121113112221121321132122311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112311332111213122112311311123112111331121113122112132113213211121332212311322113212221",
        20:"11131221131211132221232112111312111213111213211231132132211211131221131211221321123113213221123113112221131112311332211211131221131211132211121312211231131112311211232221121321132132211331121321231231121113112221121321133112132112312321123113112221121113122113121113123112112322111213211322211312113211",
        21:"311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122211311122122111312211213211312111322211213211321322113311213212322211231131122211311123113223112111311222112132113311213211221121332211211131221131211132221232112111312111213111213211231132132211211131221232112111312211213111213122112132113213221123113112221131112311311121321122112132231121113122113322113111221131221",
        22:"132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133122112231131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112131221123113111231121113311211131221121321131211132221123113112211121312211231131122211211133112111311222112111312211312111322211213211321322113311213211331121113122122211211132213211231131122212322211331222113112211",
        23:"111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121113222123112221221321132132211231131122211331121321232221123113112221131112311332111213122112311311123112112322211211131221131211132221232112111312211322111312211213211312111322211231131122111213122112311311221132211221121332211213211321322113311213212312311211131122211213211331121321123123211231131122211211131221131112311332211213211321223112111311222112132113213221123123211231132132211231131122211311123113322112111312211312111322212321121113122123211231131122113221123113221113122112132113213211121332212311322113212221",
        24:"3113112221131112311332111213122112311311123112111331121113122112132113121113222112311311221112131221123113112221121113311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112311332111213213211221113122113121113222112132113213221232112111312111213322112132113213221133112132123123112111311222112132113311213211221121332211231131122211311123113321112131221123113112221132231131122211211131221131112311332211213211321223112111311222112132113212221132221222112112322211211131221131211132221232112111312111213111213211231132132211211131221232112111312211213111213122112132113213221123113112221133112132123222112111312211312112213211231132132211211131221131211132221121311121312211213211312111322211213211321322113311213212322211231131122211311123113321112131221123113112211121312211213211321222113222112132113223113112221121113122113121113123112112322111213211322211312113211",
        25:"132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113212231121113112221121321132132211231232112311321322112311311222113111231133221121113122113121113221112131221123113111231121123222112132113213221133112132123123112111312111312212231131122211311123113322112111312211312111322111213122112311311123112112322211211131221131211132221232112111312111213111213211231132132211211131221232112111312212221121123222112132113213221133112132123123112111311222112132113213221132213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121132211332113221122112133221123113112221131112311332111213122112311311123112111331121113122112132113121113222112311311221112131221123113112221121113311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112212211131221121321131211132221123113112221131112311332211211133112111311222112111312211311123113322112111312211312111322212321121113121112133221121321132132211331121321231231121113112221121321132122311211131122211211131221131211322113322112111312211322132113213221123113112221131112311311121321122112132231121113122113322113111221131221",
        26:"1113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123211211131211121311121321123113111231131122112213211321322113311213212322211231131122211311123113223112111311222112132113311213211221121332211231131122211311123113321112131221123113111231121113311211131221121321131211132221123113112211121312211231131122113221122112133221121113122113121113222123211211131211121311121321123113213221121113122113121113222113221113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111221132221231221132221222112112322211213211321322113311213212312311211131122211213211331121321123123211231131122211211131221131112311332211213211321223112111311222112132113213221123123211231132132211231131122211311123113322112111312211312111322111213122112311311123112112322211213211321322113312211223113112221121113122113111231133221121321132132211331121321232221123123211231132132211231131122211331121321232221123113112221131112311332111213122112311311123112112322211211131221131211132221232112111312111213111213211231132132211211131221131211221321123113213221123113112221131112211322212322211231131122211322111312211312111322211213211321322113311213211331121113122122211211132213211231131122212322211331222113112211",
        27:"31131122211311123113321112131221123113111231121113311211131221121321131211132221123113112211121312211231131122211211133112111311222112111312211312111322211213211321322123211211131211121332211231131122211311122122111312211213211312111322211231131122211311123113322112111331121113112221121113122113111231133221121113122113121113222123211211131211121332211213211321322113311213211322132112311321322112111312212321121113122122211211232221123113112221131112311332111213122112311311123112111331121113122112132113311213211321222122111312211312111322212321121113121112133221121321132132211331121321132213211231132132211211131221232112111312212221121123222112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122211311123113322113223113112221131112311332211211131221131211132211121312211231131112311211232221121321132132211331221122311311222112111312211311123113322112132113213221133122211332111213112221133211322112211213322112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212321121113121112133221121311121312211213211312111322211213211321322123211211131211121332211213211321322113311213212312311211131122211213211331121321122112133221123113112221131112311332111213122112311311123112111331121113122112132113121113222112311311222113111221221113122112132113121113222112132113213221133122211332111213322112132113213221132231131122211311123113322112111312211312111322212321121113122123211231131122113221123113221113122112132113213211121332212311322113212221",
        28:"13211321322113311213212312311211131122211213211331121321123123211231131122211211131221131112311332211213211321223112111311222112132113213221123123211231132132211231131122211311123113322112111312211312111322111213122112311311123112112322211213211321322113312211223113112221121113122113111231133221121321132132211331121321232221123123211231132132211231131122211331121321232221123113112221131112311332111213122112311311123112112322211211131221131211132221232112111312211322111312211213211312111322211231131122111213122112311311221132211221121332211213211321322113311213212312311211131122211213211331121321123123211231131122211211131221232112111312211312113211223113112221131112311332111213122112311311123112112322211211131221131211132221232112111312211322111312211213211312111322211231131122111213122112311311221132211221121332211211131221131211132221232112111312111213111213211231132132211211131221232112111312211213111213122112132113213221123113112221133112132123222112111312211312112213211231132132211211131221131211322113321132211221121332211213211321322113311213212312311211131122211213211331121321123123211231131122211211131221131112311332211213211321322113311213212322211322132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221123113112221131112311332111213122112311311123112111331121113122112132113121113222112311311221112131221123113112221121113311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112212211131221121321131211132221123113112221131112311332211211133112111311222112111312211311123113322112111312211312111322212321121113121112133221121321132132211331121321132213211231132132211211131221232112111312212221121123222112311311222113111231133211121321321122111312211312111322211213211321322123211211131211121332211231131122211311123113321112131221123113111231121123222112111331121113112221121113122113111231133221121113122113121113221112131221123113111231121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122122211211232221121321132132211331121321231231121113112221121321133112132112312321123113112221121113122113111231133221121321132132211331221122311311222112111312211311123113322112111312211312111322212311322123123112112322211211131221131211132221132213211321322113311213212322211231131122211311123113321112131221123113112211121312211213211321222113222112132113223113112221121113122113121113123112112322111213211322211312113211",
        29:"11131221131211132221232112111312111213111213211231132132211211131221232112111312211213111213122112132113213221123113112221133112132123222112111312211312112213211231132132211211131221131211132221121311121312211213211312111322211213211321322113311213212322211231131122211311123113223112111311222112132113311213211221121332211211131221131211132221231122212213211321322112311311222113311213212322211211131221131211132221232112111312111213322112131112131221121321131211132221121321132132212321121113121112133221121321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111221132221231221132221222112112322211211131221131211132221232112111312111213111213211231132132211211131221232112111312211213111213122112132113213221123113112221133112132123222112111312211312111322212321121113121112133221132211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211213211321322113311213212312311211131122211213211331121321123123211231131122211211131221131112311332211213211321223112111311222112132113213221123123211231132132211231131122211311123113322112111312211312111322111213122112311311123112112322211213211321322113312211223113112221121113122113111231133221121321132132211331121321232221123123211231132132211231131122211331121321232221123113112221131112311332111213122112311311123112112322211211131221131211132221232112111312211322111312211213211312111322211231131122111213122112311311221132211221121332211213211321322113311213212312311211131211131221223113112221131112311332211211131221131211132211121312211231131112311211232221121321132132211331121321231231121113112221121321133112132112211213322112312321123113213221123113112221133112132123222112311311222113111231132231121113112221121321133112132112211213322112311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311221132211221121332211211131221131211132221232112111312111213111213211231132132211211131221232112111312211213111213122112132113213221123113112221133112132123222112111312211312111322212311222122132113213221123113112221133112132123222112311311222113111231133211121321132211121311121321122112133221123113112221131112311332211322111312211312111322212321121113121112133221121321132132211331121321231231121113112221121321132122311211131122211211131221131211322113322112111312211322132113213221123113112221131112311311121321122112132231121113122113322113111221131221",
        30:"3113112221131112311332111213122112311311123112111331121113122112132113121113222112311311221112131221123113112221121113311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112212211131221121321131211132221123113112221131112311332211211133112111311222112111312211311123113322112111312211312111322212321121113121112133221121321132132211331121321132213211231132132211211131221232112111312212221121123222112311311222113111231133211121321321122111312211312111322211213211321322123211211131211121332211231131122211311123113321112131221123113111231121123222112111331121113112221121113122113111231133221121113122113121113221112131221123113111231121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122122211211232221121321132132211331121321231231121113112221121321132132211322132113213221123113112221133112132123222112111312211312112213211231132132211211131221131211322113321132211221121332211231131122211311123113321112131221123113111231121113311211131221121321131211132221123113112211121312211231131122211211133112111311222112111312211312111322211213211321223112111311222112132113213221133122211311221122111312211312111322212321121113121112131112132112311321322112111312212321121113122122211211232221121321132132211331121321231231121113112221121321132132211322132113213221123113112221133112132123222112111312211312112213211231132132211211131221131211322113321132211221121332211213211321322113311213212312311211131122211213211331121321123123211231131122211211131221131112311332211213211321223112111311222112132113213221123123211231132132211231131122211311123113322112111312211312111322111213122112311311123112112322211213211321322113312211223113112221121113122113111231133221121321132132211331222113321112131122211332113221122112133221123113112221131112311332111213122112311311123112111331121113122112132113121113222112311311221112131221123113112221121113311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112311332111213122112311311123112112322211322311311222113111231133211121312211231131112311211232221121113122113121113222123211211131221132211131221121321131211132221123113112211121312211231131122113221122112133221121321132132211331121321231231121113121113122122311311222113111231133221121113122113121113221112131221123113111231121123222112132113213221133112132123123112111312211322311211133112111312211213211311123113223112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123211211131211121332211213111213122112132113121113222112132113213221232112111312111213322112132113213221133112132123123112111311222112132113311213211221121332211231131122211311123113321112131221123113112221132231131122211211131221131112311332211213211321223112111311222112132113212221132221222112112322211211131221131211132221232112111312111213111213211231131112311311221122132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212321121113121112131112132112311321322112111312212321121113122122211211232221121311121312211213211312111322211213211321322123211211131211121332211213211321322113311213211322132112311321322112111312212321121113122122211211232221121321132132211331121321231231121113112221121321133112132112312321123113112221121113122113111231133221121321132122311211131122211213211321222113222122211211232221123113112221131112311332111213122112311311123112111331121113122112132113121113222112311311221112131221123113112221121113311211131122211211131221131211132221121321132132212321121113121112133221123113112221131112311332111213213211221113122113121113222112132113213221232112111312111213322112132113213221133112132123123112111312211322311211133112111312212221121123222112132113213221133112132123222113223113112221131112311332111213122112311311123112112322211211131221131211132221232112111312111213111213211231132132211211131221131211221321123113213221123113112221131112211322212322211231131122211322111312211312111322211213211321322113311213211331121113122122211211132213211231131122212322211331222113112211"
    }

    return map[n]
};

Result:

  • 18/18 cases passed (56 ms)
  • Your runtime beats 98.81 % of javascript submissions
  • Your memory usage beats 98.5 % of javascript submissions (33.5 MB)
  • Time complexity O(1)

Thinking and summing up

Generally speaking, it's very simple to solve this problem with regularity, and the test point is regular matching; of course, recursion or traversal is also a conventional idea; dictionary method is a pure joy. It is recommended to use regularity to solve this problem.

53. Maximum suborder sum

Title address

Title Description

Given an integer array nums, find a continuous subarray with the largest sum (subarray contains at least one element), and return its maximum sum.

Example:

Input: [- 2,1, - 3,4, - 1,2,1, - 5,4],
Output: 6
 Explanation: the sum of continuous subarrays [4, - 1,2,1] is the largest, which is 6.

Advance:

If you have implemented the solution with O(n) complexity, try to use a more refined divide and conquer method.

Assumption of topic analysis

First of all, the basic solution of this problem must be a violent ergodic solution, which directly finds the maximum interval. Of course, we can also use dynamic programming to think about problems, list dynamic and transfer equations, which is equivalent to solving Max(d[0, i]). In addition, in the advanced level, it indicates that the divide and conquer method has been used before, and we can also take it as a direction. So there are about three kinds:

  • Traverse to solve, directly traverse to calculate the interval value
  • Dynamic programming, solving dynamic problems, finding the maximum value of each dynamic interval
  • To find the largest sum of subsequences in an interval

Note that the initial value needs to be defined as the theoretical maximum and minimum value as long as the maximum and minimum value are found.

Write code validation

I. ergodic solution

Code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    let res = Number.MIN_SAFE_INTEGER
    for(let i = 0; i < nums.length; i++) {
        let sum = 0
        // The maximum suborder and the maximum suborder at the beginning of i are calculated respectively
        for(let j = i; j < nums.length; j++) {
            sum += nums[j];
            res = Math.max(res, sum)
        }
    }
    return res
};

Result:

  • 202/202 cases passed (272 ms)
  • Your runtime beats 7.61 % of javascript submissions
  • Your memory usage beats 41.88 % of javascript submissions (35.1 MB)
  • Time complexity O(n^2)

II. Dynamic planning

Code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    let res = dp = nums[0] // Initial value
    for(let i = 1; i < nums.length; i++) {
        dp = Math.max(dp + nums[i], nums[i]) // Dynamic maximum
        res = Math.max(res, dp)
    }
    return res
};

Result:

  • 202/202 cases passed (68 ms)
  • Your runtime beats 90.14 % of javascript submissions
  • Your memory usage beats 45 % of javascript submissions (35.1 MB)
  • Time complexity O(n)

III. Divide and conquer

Code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    // Constant division
    function countByDichotomy (start, end) {
        // Stores the results on the left, the results on the right, the greater of the two, and the sum of the two
        // Explain: the largest subsequence is either over bound or unbounded in the left and right intervals.
        // If not, Max(left, right)
        // If it is out of bounds, the maximum value is the maximum value from the left to the middle plus the maximum value from the middle to the right
        if (end === start) { // Array is just one item
            return {
                lmax: nums[start], // The left half interval contains the largest sum of suborders of its right end points
                rmax: nums[start], // The right half interval contains the sum of the largest subsequences of its left end points
                sum: nums[start], // The sum
                result: nums[start] // The maximum sum of subsequences in a region
            }
        } else {
            const mid = (start + end) >>> 1 // This is explained before, so as to avoid overflow
            const left = countByDichotomy(start, mid) // Calculation results in the left interval
            const right = countByDichotomy(mid + 1, end) // Calculation results in the right interval
            return {
                lmax: Math.max(left.lmax, left.sum + right.lmax),
                rmax: Math.max(right.rmax, left.rmax + right.sum),
                sum: left.sum + right.sum,
                result: Math.max(left.rmax + right.lmax, Math.max(left.result, right.result))
            }
        }
    }
    return countByDichotomy(0, nums.length - 1).result;
};

Result:

  • 202/202 cases passed (60 ms)
  • Your runtime beats 97.89 % of javascript submissions
  • Your memory usage beats 5.01 % of javascript submissions (36.7 MB)
  • Time complexity O(n)

Consult others' solution

The following interesting ideas are found in the process of consulting the solutions:

  • Dynamic planning, using the idea of gain. In fact, the dynamic planning we wrote above is the same
  • Greedy method, try to add one more bit, take the larger value
  • Using greedy method to find interval in divide and rule

I. dynamic planning

Code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    let res = nums[0]
    let sum = nums[0] // gain
    for(let i = 1; i < nums.length; i++) {
        if (sum > 0) { // Positive gain, sum reserved plus current ergodic number
            sum += nums[i]
        } else { // sum updated to current traversal number
            sum = nums[i]
        }
        res = Math.max(res, sum)
    }
    return res
};

Result:

  • 202/202 cases passed (60 ms)
  • Your runtime beats 97.89 % of javascript submissions
  • Your memory usage beats 47.5 % of javascript submissions (35.1 MB)
  • Time complexity O(n)

II. Greedy method

Code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    let res = Number.MIN_SAFE_INTEGER // Initial value
    let sum = 0
    for(let i = 0; i < nums.length; i++) {
        sum += nums[i]
        res = Math.max(res, sum)
        if (sum < 0) { // Start to find the subsequence string again
            sum = 0;
        }
    }
    return res
};

Result:

  • 202/202 cases passed (68 ms)
  • Your runtime beats 90.14 % of javascript submissions
  • Your memory usage beats 45 % of javascript submissions (35.1 MB)
  • Time complexity O(n)

III. using greedy method to find interval in divide and rule

Code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    // Get cross boundary sum
    function getMaxCross (start, mid, end) {
        let leftRes = Number.MIN_SAFE_INTEGER
        let leftSum = 0
        for(let i = mid; i >= start; i--) {
            leftSum += nums[i]
            leftRes = Math.max(leftRes, leftSum)
        }

        let rightRes = Number.MIN_SAFE_INTEGER
        let rightSum = 0
        for(let i = mid + 1; i <= end; i++) {
            rightSum += nums[i]
            rightRes = Math.max(rightRes, rightSum)
        }

        return leftRes + rightRes
    }

    function countByDichotomy (start, end) {
        if (start === end) {
            return nums[start]
        } else {
            const mid = (start + end) >>> 1
            const leftSum = countByDichotomy(start, mid)
            const rightSum = countByDichotomy(mid + 1, end)
            const midSum = getMaxCross(start, mid, end)
            // The largest of the three is the sum of the largest suborders
            return Math.max(leftSum, rightSum, midSum)
        }
    }

    return countByDichotomy(0, nums.length - 1)
};

Result:

  • 202/202 cases passed (72 ms)
  • Your runtime beats 80.56 % of javascript submissions
  • Your memory usage beats 49.38 % of javascript submissions (35.1 MB)
  • Time complexity O(nlog(n))

Thinking and summing up

In my opinion, dynamic planning has a clear idea in solving this set of problems, and greedy method can also be understood as an extension based on traversal, while divide and conquer method needs to be understood by drawing pictures. Generally, when we see the largest and longest questions, we can basically try to answer them with dynamic planning questions.

58. Length of last word

Title address

Title Description

Given a string containing only uppercase and lowercase letters and spaces', returns the length of its last word.

If the last word does not exist, return 0.

Description: a word is a string of letters without any spaces.

Example:

Type: "Hello World"
Output: 5

Assumption of topic analysis

This question looks like a string question. We can try to answer it from the following aspects:

  • Traversal, starting from the end, high efficiency
  • lastIndexOf, find space directly
  • regular
  • split

Write code validation

I. traversal

Code:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    if(!s.length) return 0
    let i = s.length - 1
    while(i >= 0 && s.charAt(i) === ' ') {
        i--
    }
    if(i < 0) return 0 // All spaces.

    let j = i
    while(j >= 0 && s.charAt(j) != ' ') {
        j--
    }
    return i - j
};

Result:

  • 59/59 cases passed (64 ms)
  • Your runtime beats 81.14 % of javascript submissions
  • Your memory usage beats 29.72 % of javascript submissions (33.8 MB)
  • Time complexity O(n)

Ⅱ.lastIndexOf

Code:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    if(!s.length) return 0
    s = s.trim()
    const idx = s.lastIndexOf(' ')
    return idx === -1 ? s.length : s.length - 1 - idx
};

Result:

  • 59/59 cases passed (48 ms)
  • Your runtime beats 99.48 % of javascript submissions
  • Your memory usage beats 36.52 % of javascript submissions (33.7 MB)
  • Time complexity O(1)

III. Regular.

Code:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    if(!s.length) return 0
    const match = s.match(/([a-zA-Z]+)\s*$/)
    let res = 0
    if (match) {
        res = match.pop()
        return res.length
    }
    return res
};

Result:

  • 59/59 cases passed (80 ms)
  • Your runtime beats 26.65 % of javascript submissions
  • Your memory usage beats 5.95 % of javascript submissions (34.2 MB)
  • Time complexity O(1)

Ⅳ.split

Code:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    if(!s.length) return 0
    s = s.trim()
    const arr = s.split(' ')
    if (arr.length) {
        let str = arr.pop()
        return str.length
    } else {
        return 0
    }
};

Result:

  • 59/59 cases passed (60 ms)
  • Your runtime beats 90.57 % of javascript submissions
  • Your memory usage beats 13.8 % of javascript submissions (34 MB)
  • Time complexity O(1)

Consult others' solution

There is no special solution in the solution, most of which are based on class library solutions, such as String and Array methods in Javascript. Or traverse the implementation.

Thinking and summing up

Up to now, I haven't figured out where to study this question? However, I suggest that interested students can expand and realize lastIndexOf by themselves Previous issue There should be a lot to gain from the dozens of solutions to 28 problems.

66. plus one

Title address

Title Description

Given a nonnegative integer represented by a nonempty array of integers, add one to the number.

The highest number is placed at the top of the array, and each element of the array only stores a single number.

You can assume that except for the integer 0, this integer does not start with zero.

Example:

Input: [1,2,3]
Output: [1,2,4]
Explanation: the input array represents the number 123.

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: the input array represents the number 4321.

Assumption of topic analysis

There are two main directions for me to solve this problem. One is to traverse the array and solve it. The other is to turn the array into a number and then deal with it. But turning numbers may overflow, so I just want to answer from the perspective of traversal.

  • Traversal, from the back to the front, find the item not 9, then fill in 0

Write code validation

I. traversal

Code:

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    for(let i = digits.length - 1; i >= 0; i--) {
        // Can't find a number less than 9, just add 1 to output
        if(digits[i] !== 9) {
            digits[i]++
            return digits
        } else {
            digits[i] = 0
        }
    }
    digits.unshift(1)
    return digits
};

Result:

  • 109/109 cases passed (60 ms)
  • Your runtime beats 93.72 % of javascript submissions
  • Your memory usage beats 26.35 % of javascript submissions (33.8 MB)
  • Time complexity O(n)

Consult others' solution

It is found that the ideas are basically traversal, but there will be some gaps in the specific implementation. Here is just one of the simplest.

I. traversal

Code:

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    for(let i = digits.length - 1; i >= 0; i--) {
        digits[i]++
        // Take the remainder of 10, do the assignment operation, and continue to carry if it is 0
        digits[i] %= 10
        if(digits[i] !== 0) {
            return digits
        }
    }
    digits.unshift(1)
    return digits
};

Result:

  • 109/109 cases passed (64 ms)
  • Your runtime beats 85.29 % of javascript submissions
  • Your memory usage beats 94.34 % of javascript submissions (33.4 MB)
  • Time complexity O(n)

Thinking and summing up

This problem may be converted into numbers and then processed by the public, but when doing numerical operation, please remember to consider the problem of overflow. In addition, because of the addition of 1, reverse order traversal is OK. As for whether to judge whether the last bit is 9 or more than 10, I think it is a good idea to understand and avoid the tedious code.

(end)

This article is an original article, which may update knowledge points and correct errors. Therefore, please keep the original source for reprint to facilitate traceability, avoid misleading of old wrong knowledge, and have a better reading experience
If you have any help, welcome to star or fork
(for reprint, please indicate the source: https://chenjiahao.xyz)

Posted by rogeriobrito on Wed, 13 Nov 2019 05:03:42 -0800