仿站工具下載后咋做網(wǎng)站私域流量營銷
題目一:數(shù)組原型對象的最后一個元素
請你編寫一段代碼實現(xiàn)一個數(shù)組方法,使任何數(shù)組都可以調(diào)用?array.last()
?方法,這個方法將返回數(shù)組最后一個元素。如果數(shù)組中沒有元素,則返回?-1
?。
你可以假設(shè)數(shù)組是?JSON.parse
?的輸出結(jié)果。
示例 1 :
輸入:nums = [null, {}, 3] 輸出:3 解釋:調(diào)用 nums.last() 后返回最后一個元素: 3。
示例 2 :
輸入:nums = [] 輸出:-1 解釋:因為此數(shù)組沒有元素,所以應(yīng)該返回 -1。 提示:
arr
?是一個有效的 JSON 數(shù)組0 <= arr.length <= 1000
/*** @return {null|boolean|number|string|Array|Object}*/
Array.prototype.last = function() {};/*** const arr = [1, 2, 3];* arr.last(); // 3*/
解題:
方法一:
Array.prototype.last = function() {if(this.length===0){return -1;}else{return this[this.length-1] }};
方法二:
Array.prototype.last = function() {return this.length === 0 ? -1 : this[this.length - 1];
}作者:力扣官方題解
鏈接:https://leetcode.cn/problems/array-prototype-last/solutions/2506895/shu-zu-yuan-xing-dui-xiang-de-zui-hou-yi-4phe/
來源:力扣(LeetCode)
題目二:計數(shù)器
給定一個整型參數(shù)?n
,請你編寫并返回一個?counter
?函數(shù)。這個?counter
?函數(shù)最初返回?n
,每次調(diào)用它時會返回前一個值加 1 的值 (?n
?,??n + 1
?,??n + 2
?,等等)。
示例 1:
輸入: n = 10 ["call","call","call"] 輸出:[10,11,12] 解釋: counter() = 10 // 第一次調(diào)用 counter(),返回 n。 counter() = 11 // 返回上次調(diào)用的值加 1。 counter() = 12 // 返回上次調(diào)用的值加 1。
示例 2:
輸入: n = -2 ["call","call","call","call","call"] 輸出:[-2,-1,0,1,2] 解釋:counter() 最初返回 -2。然后在每個后續(xù)調(diào)用后增加 1。
提示:
-1000?<= n <= 1000
0 <= calls.length <= 1000
calls[i] === "call"
解題:
方法一:
function createCounter(n) { let count = n; // 初始化計數(shù)值為 n return function() { return count++; // 返回當(dāng)前計數(shù)值,并同時將其遞增 };
}
方法二:
var createCounter = function(n) {return function() {return n++; };
};作者:力扣官方題解
鏈接:https://leetcode.cn/problems/counter/solutions/2487678/ji-shu-qi-by-leetcode-solution-xuwj/
來源:力扣(LeetCode)