27. Remove Element&26. Remove Duplicates from Sorted Array

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.
這道題要求只能在原數組上做修改,將數組中的給定元素除去,并返回新的數組長度。最后會檢查原數組中你返回的長度的元素是否是符合要求的。
使用兩個指針的辦法,一個指針一直從前往后走檢測每一個元素,另一個指針僅當檢測到的元素不是要刪掉的元素的時候把這個元素移過來然后向后走。

/**
 * @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;
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容