JS Implementation of LeetCode Array Class Algorithms (6)

Keywords: github Programming

See more algorithm implementations: https://github.com/Erindcl/Daily-algorithm

 

724. Find the central index of the array

  • Given an array nums of integer type, write a method that returns the array "central index".
  • This is how we define the array central index: the sum of all elements on the left side of the array central index is equal to the sum of all elements on the right side.
  • If the array does not have a central index, then we should return - 1. If the array has multiple central indexes, we should return to the nearest one to the left.

Analysis: Traverse the array and calculate the sum of the left and right elements of i. When the two sides are equal, i is the central index. The code is as follows:

var pivotIndex = function(nums) {
    let len = nums.length;
    for (let i = 0; i < len; i++) {
        let sumL = 0, sumR = 0;
        for(let j = 0; j < i; j++) {
            sumL += nums[j];
        }
        for(let k = i + 1; k < len; k++) {
            sumR += nums[k];
        }
        if (sumR == sumL) {
            return i;
        }
    }
    return -1;
};

Other implementations:

var pivotIndex = function(nums) {
    let len = nums.length, currS = 0;
    let sum = nums.reduce((a,b) => a+b, 0); // Calculating the sum of arrays using reduce accumulator
    for (let i = 0; i < len; i++) {
        if (sum == currS * 2 + nums[i]) {
            return i;
        }
        currS += nums[i];
    }
    return -1;
};

746. Use minimum cost to climb stairs

  • Each index of the array acts as a ladder, and the first ladder corresponds to a non-negative physical cost[i] (the index starts at 0).
  • Every time you climb a staircase, you have to spend the corresponding physical cost, and then you can choose to continue climbing a staircase or two staircases.
  • You need to find the minimum cost to reach the top of the floor. At the beginning, you can choose elements with index 0 or 1 as the initial step.

Analysis: Dynamic programming: find the key equation of state dp[i] = min(dp[i-1], dp[i-2])+cost[i], so that each position of the DP array can store the current minimum answer. The code is as follows:

var minCostClimbingStairs = function(cost) {
    let len = cost.length;
    if (len <= 2) {
        return 0;
    }
    let dp = [cost[0],cost[1]]; 
    for (let i = 2; i < len; i++) {
        let curr = Math.min(dp[i-1],dp[i-2]) + cost[i];
        dp.push(curr);
    }
    return Math.min(dp[len - 1],dp[len - 2]);
};

Other implementations:

var minCostClimbingStairs = function(cost) {
    for(let i = 2; i < cost.length; i++) {
        cost[i] = cost[i] + Math.min(cost[i - 1], cost[i - 2]);
    }
    return Math.min(cost[cost.length - 1], cost[cost.length - 2]);
}

747. At least twice the maximum number of other numbers

  • In a given array nums, there is always a maximum element.
  • Find if the largest element in an array is at least twice as large as every other number in the array.
  • If so, the index of the largest element is returned, otherwise - 1 is returned.

The code is as follows:

var dominantIndex = function(nums) {
    let max = Math.max(...nums);
    let maxIndex = nums.indexOf(max);
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] != max && max / 2 < nums[i]) {
            return -1;
        }
    }
    return maxIndex;
};

766. Toplitz matrix

  • If each direction of a matrix has the same element on the diagonal line from the top left to the bottom right, then the matrix is a Toplitz matrix.
  • Given a matrix of M x N, return True if and only if it is a Toplitz matrix.

The code is as follows:

var isToeplitzMatrix = function(matrix) {
    let lenN = matrix.length;
    let lenM = matrix[0].length;
    for (let i = 0; i < lenN - 1; i++) {
        for (let j = 0; j < lenM - 1; j++) {
            if (matrix[i][j] != matrix[i+1][j+1]) {
                return false;
            }
        }
    }
    return true;
};

830. Location of larger groups

  • In a string S consisting of lowercase letters, a group consisting of consecutive identical characters is included.
  • For example, in the string S = abbxxxxxzyy, there are groupings such as "a", "bb", "xxxx", "z" and "yy".
  • We call all groups containing more than or equal to three consecutive characters larger. Find the starting and ending positions for each larger group.
  • The final results are output in dictionary order.

The code is as follows:

var largeGroupPositions = function(S) {
    let map = new Map(), currIndex = 0, currS = S[0];
    let result = [], sArr = S.split('');
    for (let i = 1; i < S.length; i++) {
        if (S[i] == S[i-1]) {
            currS += S[i];
        } else {
            if (currS.length >= 3) {
                let currArr = [currIndex, parseInt(currIndex) + parseInt(currS.length) - 1];
                result.push(currArr);
            }
            currIndex = i;
            currS = S[i];
        }
    }
    if (currS.length >= 3) {
        let currArr = [currIndex, parseInt(currIndex) + parseInt(currS.length) - 1];
        result.push(currArr);
    }
    return result;
};

Other implementations:

var largeGroupPositions = function(S) {
    let outPut=[]
    let reg=/([a-z])\1\1+/g
    let out=reg.exec(S)
    while(out)
        {
            outPut.push([out.index,out.index+out[0].length-1])
            out=reg.exec(S)
        }
    return outPut
}; 

 

 

Posted by margarette_a on Sat, 11 May 2019 05:22:56 -0700