[Employment front-end evil compensation algorithm]JavaScript leetcode top100 (5): Addition of two numbers, longest substring without repeating characters, longest palindrome substring, container holding the most water, sum of three numbers

Column statement: Just use the simplest and easy-to-understand method to pass, don't seek optimization, don't spray if you don't like it,
update five medium-difficulty questions today:

add two numbers

  • Question
    You are given two non-empty linked lists representing two non-negative integers. Each of their digits is stored in reverse order, and each node can only store one digit.
    Please add two numbers and return a linked list representing the sum in the same form.
    You can assume that neither number starts with a zero other than the number zero.

  • Knowledge points:
    linked list, simulation

  • The idea
    is to simulate the operation of addition, because it is a digital linked list in reverse order, so we can traverse the linked list from the head of the two linked lists, add the two numbers each time and add a carry mark (whether there is a carry in the last result), and put it in In the new linked list, the result of the addition exceeds 10, we take the remainder of 10, and then store the carry in a carry flag. If there is a linked list at the end, then when adding this time, it is 0. Traverse the two linked
    lists , until the two linked lists are traversed to the bottom, and the carry is 0

  • the code

var addTwoNumbers = function(l1, l2) {
    
    
    let head = null, tail = null;
    let carry = 0;
    while (l1 || l2) {
    
    
        const n1 = l1 ? l1.val : 0;
        const n2 = l2 ? l2.val : 0;
        const sum = n1 + n2 + carry;
        if (!head) {
    
    
            head = tail = new ListNode(sum % 10);
        } else {
    
    
            tail.next = new ListNode(sum % 10);
            tail = tail.next;
        }
        carry = Math.floor(sum / 10);
        if (l1) {
    
    
            l1 = l1.next;
        }
        if (l2) {
    
    
            l2 = l2.next;
        }
    }
    if (carry > 0) {
    
    
        tail.next = new ListNode(carry);
    }
    return head;
};

Longest substring without repeating characters

  • Topic
    Given a string s, please find the length of the longest substring that does not contain repeated characters.
  • Knowledge point
    string, hash table, sliding window
  • Ideas
    Initialize a hash table to store our characters, traverse our string, and then use another variable to record the beginning of the current string.
    Every time a character is encountered, if it has never appeared, then we record it directly Into the hash table, and then update the length.
    If it has appeared, then we update the beginning position of the string, and the beginning position moves forward. During this period, the letters passed are deleted from the hash table until the letter position that is being traversed is deleted, and then the Now the traversed letters are recorded in the hash table, and finally the length is updated
  • the code
var lengthOfLongestSubstring = function (s) {
    
    
    let hash = new Array(200).fill(0);
    let a = 0;
    let max = 0;
    for (var i = 0; i < s.length; i++) {
    
    
        let t = s.charCodeAt(i);
        if(hash[t] != 0 ){
    
    
            while(s[a]!=s[i]){
    
    
                hash[s.charCodeAt(a)] = 0;
                a++;
            }
            hash[s.charCodeAt(a)] = 0;
            a++;
        }
        max = Math.max(i - a + 1,max);
        hash[t] = 1;
    }
    return max;
};

longest palindromic substring

  • Question
    Given a string s, find the longest palindromic substring in s.
    A string is called a palindrome if the reverse order of the string is the same as the original string.
  • Knowledge point
    palindrome string, dynamic programming
  • Ideas
    We use a two-digit array to record whether there is a palindrome between [ i , j ], we traverse each bit, it has three situations: when traversing
    i and itself, it must be a palindrome, recorded as true
    When traversing i and i + 1, only these two numbers are equal, they are palindrome strings, otherwise not
    when traversing i and i + 2 and above, they need to be equal, and i + 1 and j - 1 It is also a palindrome, it is a palindrome
    For each set of i and j, if it is a palindrome and longer than the current record, update the returned palindrome
  • the code
var longestPalindrome = function (s) {
    
    
    var n = s.length;
    var d = [];
    for (var k = 0; k < n; k++) {
    
    
        d.push([]);
    }
    var ans = '';
    var j;
    for (var l = 1; l <= n; l++) {
    
    
        for (var i = 0; i < n; i++) {
    
    
            j = i + l - 1;
            if (j >= n) break;
            if (i == j) d[i][j] = true;
            else if (j == i + 1) d[i][j] = (s[i] == s[j])
            else {
    
    
                d[i][j] = d[i + 1][j - 1] && (s[i] == s[j])
            }
            if (d[i][j]) {
    
    
                ans = s.slice(i, j + 1);
            }
        }
    }
    return ans;
};

Container that holds the most water

  • Topic
    Given an integer array height of length n. There are n vertical lines, and the two endpoints of the i-th line are (i, 0) and (i, height[i]).
    Find two of these lines such that, together with the x-axis, they form a container that holds the most water.
    Returns the maximum amount of water the container can store.
    Instructions: You cannot tilt the container.
  • Knowledge point
    double pointer, greedy
  • Idea
    We use two pointers to update our container, one pointing to the subscript 0 and one pointing to the last bit of the array, each time we update the shorter of the two pointers, and then calculate their water holding capacity, until the two pointers meet
  • the code
var maxArea = function (height) {
    
    
    let b = height.length;
    let max = 0;
    let i = 0;
    let j = b;
    while (i < j) {
    
    
        let area = Math.min(height[i], height[j]) * (j - i);
        if (area > max) {
    
    
            max = area
        }
        if (height[j] > height[i]) {
    
    
            i++;
        }
        else {
    
    
            j--;
        }
    }
    return max;
};

sum of three numbers

  • The title
    gives you an integer array nums, and judge whether there is a triplet [nums[i], nums[j], nums[k]] that satisfies i != j, i != k and j != k, and also satisfies nums[i] + nums[j] + nums[k] == 0 . Please return all triples whose sum is 0 and are not repeated.
    Note: Duplicate triplets are not allowed in the answer.
  • knowledge point
    double pointer
  • The idea is
    to sort our array first. Only ordered arrays can use double pointers, and then traverse each bit. For each bit i, we use two pointers to find the remaining two numbers we need, and their sum must be equal to 0 - nums [ i ], one thing to note is that it cannot be repeated, so we only calculate the item closest to another pointer among the same elements each time
  • the code
var threeSum = function (nums) {
    
    
    var ret = [];
    nums.sort(function (a, b) {
    
    
        return a - b;
    })
    for (var i = 0; i < nums.length - 1; i++) {
    
    
        var a = i + 1;
        var b = nums.length - 1;
        if (i != 0 && nums[i] == nums[i - 1]) {
    
    
            continue;
        }
        var re = 0 - nums[i];
        while (a < b) {
    
    
            if (nums[a] + nums[b] < re) {
    
    
                a++;
                while (nums[a - 1] == nums[a]) {
    
    
                    a++;
                }
            } else if (nums[a] + nums[b] > re) {
    
    
                b--;
                while (nums[b + 1] == nums[b]) {
    
    
                    b--;
                }
            } else {
    
    
                ret.push([nums[a], nums[i], nums[b]]);
                a++;
                while (nums[a - 1] == nums[a]) {
    
    
                    a++;
                }
                b--;
                while (nums[b + 1] == nums[b]) {
    
    
                    b--;
                }
            }
        }
    }
    return ret;
};

Guess you like

Origin blog.csdn.net/weixin_46463785/article/details/129907158