leetcode_p26_移除数组中重复的元素——js实现

2018-01-23  本文已影响0人  kayleeWei

题目

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 by modifying the input array in-place with O(1) extra memory.

Example:
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.</pre>

解题思路

用两个变量i,j记录数组位置,从左向右遍历数组。一旦检测到不重复的元素,就直接覆盖之前检测到的重复元素的位置。
若该数组有n个不重复的元素,保证最后数组的前n个是不重复的元素值,并返回不重复的元素个数

var removeDuplicates = function(nums) {
    if(nums.length <= 1) {
        return nums.length
    }

    var i = 0, j = 0;
    while(j < nums.length) {
        if (nums[i] == nums[j]) {
            j++;
        } else {
            i++;
            nums[i] = nums [j];
            j++;
        }
    }
    return i + 1;
};
上一篇下一篇

猜你喜欢

热点阅读