Javascript面试常见算法——来自freecodecamp

找到对等分差

知识提要:对称差 (Symmetric Difference),数学上,两个集合的对称差分是只属于其中一个集合,而不属于另一个集合的元素组成的集合,例如:集合let A = [ 1, 2, 3]和let B = [ 2, 3, 4]的对称差分为A △ B = C = [ 1, 4]。 集合论中的这个运算相当于布尔逻辑中的异或运算。

创建一个函数 sym,输入两个或两个以上的数组作为参数,然后返回值为对称差分的数组

思路:设定两个数组 (例如:let A = [1, 2, 3],let B = [2, 3, 4])作为参数传入,返回对称差分数组(A △ B = C = [1, 4]),且数组中没有重复项。

function sym() {
      var args = [];
      for (var i = 0; i < arguments.length; i++) {
        args.push(arguments[i]);
      }

      function symDiff(arrayOne, arrayTwo) {
        var result = [];

        arrayOne.forEach(function(item) {
          if (arrayTwo.indexOf(item) < 0 && result.indexOf(item) < 0) {
            result.push(item);
          }
        });

        arrayTwo.forEach(function(item) {
          if (arrayOne.indexOf(item) < 0 && result.indexOf(item) < 0) {
            result.push(item);
          }
        });

        return result;
      }

      // Apply reduce method to args array, using the symDiff function
      return args.reduce(symDiff);
    }
 function sym() {
      let argv = Array.from(arguments).reduce(diffArray);
      return argv.filter((element, index, array) => index === array.indexOf(element));//remove duplicates
    }

    function diffArray(arr1, arr2) {
      return arr1
        .filter(element => !arr2.includes(element))
        .concat(arr2.filter(element => !arr1.includes(element)));
    }

    // test here
    sym([1, 2, 3], [5, 2, 1, 4]);

补充数组去重的方法

function unique(a) {
 
  var res = a.filter(function(item, index, array) {
    return array.indexOf(item) === index;
  });
  
  return res;
}
 
 
var a = [1, 1, '1', '2', 1];
var ans = unique(a);
console.log(ans);//[1, '1', '2',]

更新库存

创建一个二维数组,比较并更新存储在二维数组中的“库存”元素,然后并将其与新产生的第二个二维数组进行对比,更新当前的 ”库存“ 项的数量(arr1),如果找不到这个对比对象,那么将新的对象和数量添加到“库存”数组中。注意:返回的“库存”数组应该是按照数组元素的首字母顺序排序。

function updateInventory(arr1, arr2) {

        // Variable for location of product
        var index;

        // A helper method to return the index of a specified product (undefined if not found)
        var getProductIndex = function (name) {
            for (var i = 0; i < this.length; i++) {
                if (this[i][1] === name) {
                    return i;
                }
            }
            return undefined;
        }

        // For each item of the new Inventory
        for (var i = 0; i < arr2.length; i++) {

            // Invoke our helper function using arr1 as this
            index = getProductIndex.call(arr1, arr2[i][1]);

            // If the item doesn't exist
            if (index === undefined) {
                // Push the entire item
                arr1.push(arr2[i]);
            } else {
                // Add the new quantity of the current item
                arr1[index][0] += arr2[i][0];
            }

        }

        // Sort alphabetically, by the product name of each item
        arr1.sort(function (a, b) {
            if (a[1] > b[1]) {
                return 1;
            }
            if (a[1] < b[1]) {
                return -1;
            }
            return 0;
        });

        return arr1;
    }

    // test here
    // Example inventory lists
    var curInv = [
        [21, "Bowling Ball"],
        [2, "Dirty Sock"],
        [1, "Hair Pin"],
        [5, "Microphone"]
    ];

    var newInv = [
        [2, "Hair Pin"],
        [3, "Half-Eaten Apple"],
        [67, "Bowling Ball"],
        [7, "Toothpaste"]
    ];

    updateInventory(curInv, newInv);
 function updateInventory(arr1, arr2) {
      // All inventory must be accounted for or you're fired!

      var index;
      var arrCurInvName = []; // Names of arr1's items
      var arrNeInvName = []; // Names of arr2's items

      // Same as using two for loops, this takes care of increasing the number of stock quantity.
      arr1.map(function(item1) {
        return arr2.map(function(item2) {
          if (item1[1] === item2[1]) {
            item1[0] = item1[0] + item2[0]; //Increase number of stock
          }
        });
      });

      // Get item's name for new Inventory
      arr2.map(function(item) {
        arrNeInvName.push(item[1]);
      });

      // Get item's name for Current Inventory
      arr1.map(function(item) {
        arrCurInvName.push(item[1]);
      });

      // Add new inventory items to current inventory.
      arrNeInvName.map(function(item) {
        if (arrCurInvName.indexOf(item) === -1) {
          index = arrNeInvName.indexOf(item);
          arr1.push(arr2[index]);
        }
      });

      // Sort the array alphabetically using the second element of the array as base.
      arr1.sort(function(currItem, nextItem) {

        //Ternary function to avoid using if else
        return currItem[1] > nextItem[1] ? 1 : -1;
      });

      return arr1;
    }

    // test here
    // Example inventory lists
    var curInv = [
        [21, "Bowling Ball"],
        [2, "Dirty Sock"],
        [1, "Hair Pin"],
        [5, "Microphone"]
    ];

    var newInv = [
        [2, "Hair Pin"],
        [3, "Half-Eaten Apple"],
        [67, "Bowling Ball"],
        [7, "Toothpaste"]
    ];

    updateInventory(curInv, newInv);
function updateInventory(arr1, arr2) {
      // All inventory must be accounted for or you're fired!

      // convert current inventory (arr1) to an one-dimensional array
      const inventory = Array.prototype.concat.apply([], arr1);

      // loop through new delivery (arr2)
      for (let i = 0; i < arr2.length; i++) {

        // extract item properties for easy reference
        const item = arr2[i][1];
        const quantity = arr2[i][0];

        // check if item already exists in inventory
        const position = inventory.indexOf(item);

        // exsisting item: update quantity
        if (position !== -1) {
          const row = Math.floor(position / 2);
          arr1[row][0] += quantity;
          continue;
        }

        // alien item: add to inventory
        arr1.push([quantity, item]);

      }

      // sort inventory in alphabetical order
      arr1.sort((previous, next) => (previous[1] > [next[1]]) ? 1 : -1);

      return arr1;

    }


    // test here
    // Example inventory lists
    var curInv = [
        [21, "Bowling Ball"],
        [2, "Dirty Sock"],
        [1, "Hair Pin"],
        [5, "Microphone"]
    ];

    var newInv = [
        [2, "Hair Pin"],
        [3, "Half-Eaten Apple"],
        [67, "Bowling Ball"],
        [7, "Toothpaste"]
    ];

    updateInventory(curInv, newInv);

请不要重复

把一个字符串中的所有的字符重新排列,然后生成一个新的字符串,返回的新字符串中没有连续重复的字符。连续重复是以单个字符为判断标准。

例如:aab应该返回 2, 因为它总共有 6 种排列方式: aab, aab, aba, aba, baa, baa,但是其中只有 2 个没有连续重复的字符(字符 a 是本例中的重复字符):aba,aba

function permAlone(str) {

  // Create a regex to match repeated consecutive characters.
  var regex = /(.)\1+/g;

  // Split the string into an array of characters.
  var arr = str.split('');
  var permutations = [];
  var tmp;

  // Return 0 if str contains same character.
  if (str.match(regex) !== null && str.match(regex)[0] === str) return 0;

  // Function to swap variables' content.
  function swap(index1, index2) {
    tmp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = tmp;
  }

  // Generate arrays of permutations using the algorithm.
  function generate(int) {
    if (int === 1) {
      // Make sure to join the characters as we create  the permutation arrays
      permutations.push(arr.join(''));
    } else {
      for (var i = 0; i != int; ++i) {
        generate(int - 1);
        swap(int % 2 ? 0 : i, int - 1);
      }
    }
  }

  generate(arr.length);

  // Filter the array of repeated permutations.
  var filtered = permutations.filter(function(string) {
    return !string.match(regex);
  });

  // Return how many have no repetitions.
  return filtered.length;
}

// Test here.
permAlone('aab');

regex contains the regular expression to match repeated consecutive characters.
The string str is split into an array of characters, arr.
0 is returned if str contains same characters.
The function swap() is used for the purpose of swapping the contents of two variable’s contents.
The next block of code uses Heap’s algorithm to generate arrays of permutations in permutations.
The filtered variable filters permutations to include only non-repeated permutations.
filtered.length returns the number of total permutations of the provided string that don’t have repeated consecutive letters.

快速排序

现在我们开始讨论快速排序。快速排序是一种高效的递归分治方法来排序数组。在这个方法中,需要在原始数组中选择一个枢轴值,然后将数组划分为两个子数组,其值大于或者小于枢轴值,然后我们将递归调用两个子数组上的快速排序算法的结果来配合使用,直到空数组或者单个元素的数组的情况,然后返回结果。递归调用的展开结果将返回的是排序后的数组。

快速排序是一种非常有效的排序方式,平均时间复杂度为O(nlog(n)),同时它也是相对比较容易实现的方式。这些特性使得快速排序成为了一种流行而有用的排序方式。

说明:创建一个函数并命名为quickSort,输入参数是一个数组,且数组元素全部都是整数类型,然后按照从最小到最大的顺序返回整个数组。虽然选择一个枢轴值很重要,但任何一个枢轴都能满足要求,为了以防万一,我嘛一般选择第一个或者最后一个元素来作为数轴值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值