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ù)組長度。最后會(huì)檢查原數(shù)組中你返回的長度的元素是否是符合要求的。
使用兩個(gè)指針的辦法,一個(gè)指針一直從前往后走檢測每一個(gè)元素,另一個(gè)指針僅當(dāng)檢測到的元素不是要?jiǎng)h掉的元素的時(shí)候把這個(gè)元素移過來然后向后走。
/**
* @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;
};