美文网首页
leetcode_p26_移除数组中重复的元素——js实现

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

作者: kayleeWei | 来源:发表于2018-01-23 22:54 被阅读0次

    题目

    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;
    };
    

    相关文章

      网友评论

          本文标题:leetcode_p26_移除数组中重复的元素——js实现

          本文链接:https://www.haomeiwen.com/subject/nkgeaxtx.html