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;
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容