没什么好说的,周末可能要加班,但是需要使用的接口,页面什么的同事都还没有弄好了,就算加班也没什么可以做的。。。。
题目
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写的代码,可能更有帮助一些。行吧,今天就先这样了。