LeetCode JavaScript解答(5):No.27 Remove Element
沒什麼好說的,週末可能要加班,但是需要使用的介面,頁面什麼的同事都還沒有弄好了,就算加班也沒什麼可以做的。。。。
題目
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
題目解析
No.27和上一篇的No.26十分相像,都是要求再不使用新陣列的情況下對原陣列進行操作並返回操作後的陣列長度,除了操作不同外,解決方法的核心思想還是一樣的,沒什麼好說的,下面上程式碼。
JS程式碼
這次依舊使用的是JavaScript的splice方法,對於這種對原陣列進行刪除操作的題目來說,splice真的是特別好用。我個人感覺需要著重提一下的是程式碼中為什麼要在使用splice方法後對i進行i–操作做的原因。這是因為若陣列中存在連續兩個數等於val,若不i–返回當前位置的話,則接下來直接從下一個數開始比較,導致只刪除一個的情況發生,所以我們需要通過i–回退一位,重新從上一步來進行重新對當前位置進行比較等操作。
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
for(i=0;i<nums.length;i++){
if(nums[i] == val){
nums.splice(i,1);
i--;
}
}
return nums.length;
};
JS的話感覺也就這樣了,其實這一題我感覺還是自己想一想看一看別人用Java或C寫的程式碼,可能更有幫助一些。行吧,今天就先這樣了。