美文网首页
80. Remove Duplicates from Sorte

80. Remove Duplicates from Sorte

作者: 菁卡因 | 来源:发表于2016-11-30 20:05 被阅读0次

    Follow up for "Remove Duplicates":
    What if duplicates are allowed at most twice?
    For example,Given sorted array nums = [1,1,1,2,2,3],
    Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
    题目:将有序数组中出现次数大于2的数更改为出现2次,返回最终数组的长度
    思路:因为题目给的是有序数组,所以依次序将每一种数的出现次数记录在sum数组中,如果出现次数大于2就删除后面出现的重复数。

    /**
     * @param {number[]} nums 已知数组
     * @return {number}
     */
         var removeDuplicates = function(nums) {
         var i , j, n;
         var sum = [];
         var len = nums.length;
         for(i=0;i<len;i++)
             sum[i] = 1;
         for(i=0,j=0;i<len;i++)
         {
             if(nums[i] == nums[i+1])
                 sum[j] = Number(sum[j])+1;
             else j++;
         }
         for(i=0,n=0;i<nums.length;i++)
         {
             j = sum[n++];
             if(j>2)
             {
                 nums.splice(i+2,j-2);
                 i++;
             }
             else if(j==2)
                 i++;
         }
         return nums.length;
       };

    相关文章

      网友评论

          本文标题:80. Remove Duplicates from Sorte

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