FCC算法题--Inventory Update
题目:
依照一个存着新进货物的二维数组,更新存着现有库存(在 arr1
中)的二维数组. 如果货物已存在则更新数量 . 如果没有对应货物则把其加入到数组中,更新最新的数量. 返回当前的库存数组,且按货物名称的字母顺序排列.
当你遇到困难的时候,记得查看错误提示、阅读文档、搜索、提问。
这是一些对你有帮助的资源:
1 function updateInventory(arr1, arr2) { 2 // All inventory must be accounted for or you're fired! 3 4 5 var arr = []; // 用于存放当前货物名称的数组 6 var obj = {}; // 用于存放当前货物名称和数组下标的对象 7 var arr1Len = arr1.length - 1; 8 9 // 遍历当前货物的名称,下标和名称 10 for (var i = 0; i < arr1.length; i++) { 11 arr.push(arr1[i][1]); 12 obj[arr1[i][1]] = i; 13 } 14 15 // 更新当前数组 16 for (var j = 0; j < arr2.length; j++) { 17 // 如果新进货物已存在,更新数量(加法) 18 if (arr.indexOf(arr2[j][1]) !== -1) { 19 var arr1Index = obj[arr2[j][1]]; 20 arr1[arr1Index][0] += arr2[j][0]; 21 } 22 // 如果新进货物不存在,加入到当前货物数组 23 else { 24 arr1.push(arr2[j]); 25 // 更新arr、obj 26 arr.push(arr2[j][1]); 27 arr1Len += 1; 28 obj[arr2[j][1]] = arr1Len; 29 } 30 } 31 32 //排序 33 arr.sort(); 34 var result = []; 35 for (var z = 0; z < arr.length; z++) { 36 result.push(arr1[obj[arr[z]]]); 37 } 38 return result; 39 40 } 41 42 // Example inventory lists 43 // arr1 44 var curInv = [ 45 [21, "Bowling Ball"], 46 [2, "Dirty Sock"], 47 [1, "Hair Pin"], 48 [5, "Microphone"] 49 ]; 50 //arr2 51 var newInv = [ 52 [2, "Hair Pin"], 53 [3, "Half-Eaten Apple"], 54 [67, "Bowling Ball"], 55 [7, "Toothpaste"] 56 ]; 57 58 updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]);
updateInventory()
应该返回一个数组.updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length
应该返回一个长度为6的数组.updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
应该返回 [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]
.updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])
应该返回 [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]
.updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
应该返回 [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]
.updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])
应该返回 [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]
.---------------------------------------------------------------------------------------