27. Remove Element
Given an array and a value, 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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
這道題要求只能在原數(shù)組上做修改恩商,將數(shù)組中的給定元素除去孝扛,并返回新的數(shù)組長度芦鳍。最后會檢查原數(shù)組中你返回的長度的元素是否是符合要求的垒玲。
使用兩個指針的辦法坐昙,一個指針一直從前往后走檢測每一個元素亏栈,另一個指針僅當(dāng)檢測到的元素不是要刪掉的元素的時候把這個元素移過來然后向后走。
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
var tail = 0;
var num = nums.length;
for (var i = 0; i < num; i++) {
if (nums[i]!==val) {
nums[tail] = nums[i];
tail++;
}
}
return tail;
};
26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
同樣的思想:
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
if (nums.length<2)
return nums.length;
var tail = 0;
var num = nums.length;
for (var i = 0; i < num; i++) {
if (nums[i]!==nums[i+1]) {
nums[tail] = nums[i];
tail++;
}
}
return tail;
};