[Unemployed front-end evil supplement algorithm]JavaScript leetcode top100 (six): grouping of anagrams, longest continuous sequence, finding all anagrams in a string, the largest sub-array sum, and the product of an array other than itself

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

49. Anagram grouping

Title

Given an array of strings, please combine anagrams together. The list of results can be returned in any order.

An anagram is a new word obtained by rearranging all the letters of a source word.

Knowledge points:

hash table, sort

train of thought

A little trick of the js language is used here. We can use the split api to convert the string into an array of characters, and then we sort the obtained array, so that the anagrams get the consistency of the result string, and then we The hash table saves the subscript of the array corresponding to the result string in the output two-digit array, and we can find the position where each string should be inserted according to this subscript

the code
/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function (strs) {
    
    
    var obj = {
    
    

    };
    let re = [];

    for (var i = 0; i < strs.length; i++) {
    
    

        let key = strs[i].split('').sort().join('');
        if (typeof obj[key] == 'undefined') {
    
    
            re.push([strs[i]]);
            obj[key] = re.length - 1;
        } else {
    
    
            re[obj[key]].push(strs[i]);
        }
    }
    return re;
};

128. Longest Consecutive Sequence

Title

Given an unsorted integer array nums, find the length of the longest sequence of consecutive numbers (it is not required that the elements of the sequence are consecutive in the original array).
Please design and implement an algorithm with O(n) time complexity to solve this problem.

Knowledge points:

Hash table, Set

train of thought

Traversing twice, the first time the data is stored in the set, the purpose is to remove duplicate elements, and then traverse the set, if the element of the current element -1 is not in the array, it means that the current element is the leftmost element of a sequence, Then use it as the starting point to search forward for the sequence that increases in order until the next bit position cannot be found, record its length, and output the longest length.

the code
/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function (nums) {
    
    
    let num_set = new Set();

    for (var i = 0; i < nums.length; i++) {
    
    
        num_set.add(nums[i]);
    }

    let re = 0;

    for (const num of num_set) {
    
    

        if (!num_set.has(num - 1)) {
    
    
            let s = 0;
            while (num_set.has(num + s)) {
    
    
                s++;
            }
            re = Math.max(re, s);
        }
    }
    return re;
};

438. Find All Alphabetic Words in a String

Title

Given two strings s and p, find all anagram substrings of p in s, and return the starting indices of these substrings. The order in which answers are output is not considered.

An anagram refers to a character string (including the same character string) formed by rearranging the same letter.

Knowledge points:

hash table, sliding window

train of thought

We first open a 26-bit hash table to store the number of occurrences of each character, and then hash the target string p

This trick uses a js language. If we use the toString method on the array, it will return a ,string composed of each split array element. If we use the toString method on the two hash tables, if they The same, the obtained string is also the same, we can use this method to quickly determine the anagram

Afterwards, we perform a sliding window operation on the s string, and now select the first area with the same size as p, and process each character in it into the hash table. If the hash table and p hash results are the same at this time, then Record this subscript, then we move one bit backward, remove the first character of the last round result in the hash table and add the next new character, and then perform an equality comparison until the entire s string is traversed, and finally output The result can be:

the code
/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function (s, p) {
    
    

    let h1 = new Array(26).fill(0);
    let h2 = new Array(26).fill(0);

    for (var i = 0; i < p.length; i++) {
    
    
        h2[p.charCodeAt(i) - "a".charCodeAt(0)]++;
    }
    let now = 0;
    let re = [];
    for (var i = 0; i < s.length; i++) {
    
    
        h1[s.charCodeAt(i) - "a".charCodeAt(0)]++;
        now++;
        if(now == p.length){
    
    
            if(h1.toString() == h2.toString()){
    
    
                re.push(i - p.length + 1);
            }
            h1[s.charCodeAt(i - p.length + 1) - "a".charCodeAt(0)]--;
            now--;
        }  
    }
    return re;
};

53. Maximum Subarray Sum

Title

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

Knowledge points:

dynamic programming

train of thought

Typical dynamic programming question: For each bit, if the maximum sum of the consecutive sub-arrays of the previous bit is negative, then adding it must be smaller than not adding it, so recalculate the sub-array directly from the current bit is the optimal solution, otherwise it is the maximum sum of the continuous sub-arrays of the previous bit plus the current bit is the maximum sum of the continuous sub-arrays of the current bit. We process each bit in turn according to this idea, update the maximum value that appears each time, and finally output:

the code
/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function (nums) {
    
    
    var dp = [];
    dp[0] = 0;
    let re = -10000;
    for (var i = 1; i <= nums.length; i++) {
    
    
        dp[i] = Math.max(dp[i-1],0)+nums[i-1];
        re = Math.max(re,dp[i]);
    }
    return re;
};

238. Product of an array other than itself

Title

Given an integer array nums, return the array answer, where answer[i] is equal to the product of all elements in nums except nums[i].

The title data guarantees that the product of all prefix elements and suffixes of any element in the array nums is within the range of 32-bit integers.

Please don't use division and solve this problem in O(n) time complexity.

Knowledge points:

prefix and

train of thought

For the classic prefix and title, we use two arrays of head and back for preprocessing:

  • head represents the product of multiplying the number starting from subscript 0 to i -1
  • back represents the product of multiplying the number from the last digit of the subscript to the i + 1 in turn
    , then the i-th digit of our end array is the end of back[i] * head[i], and the output can be processed sequentially
the code
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var productExceptSelf = function (nums) {
    
    

    let head = new Array(nums.length).fill(1);
    let back = new Array(nums.length).fill(1);

    for (var i = 1; i < nums.length; i++) {
    
    
        head[i] = head[i - 1] * nums[i - 1];
    }
    for (var i = nums.length - 2; i >= 0; i--) {
    
    
        back[i] = back[i + 1] * nums[i + 1];
    }
    for (var i = 0; i < nums.length; i++) {
    
    

        nums[i] = back[i] * head[i];
    }
    return nums;
};

Guess you like

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