zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Remove Duplicates from Sorted Array II

    Remove Duplicates from Sorted Array II

    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 1122 and 3. It doesn't matter what you leave beyond the new length.

    https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/


    删除数组中重复出现三次或三次以上的数。

    两个变量记录上次和上上的值,比较一下,如果出现大于等于三次了,记下下标。

    删除的时候要从后往前,这样不会打乱下标的顺序。

     1 /**
     2  * @param {number[]} nums
     3  * @return {number}
     4  */
     5 var removeDuplicates = function(nums) {
     6     var aRemove = [], i, previous, previous2;
     7     for(i = 0; i < nums.length; i++){
     8         if(nums[i] !== previous){
     9             //first time
    10         }else if(nums[i] === previous && nums[i] !== previous2){
    11             //duplicate two times
    12         }else{
    13             //duplicate more than two times
    14             aRemove.push(i);
    15         }
    16         previous2 = previous;
    17         previous = nums[i];
    18     }
    19     for(i = aRemove.length - 1; i >= 0; i--){
    20         nums.splice(aRemove[i], 1);
    21     }
    22     return nums.length;
    23 };

    另一种更简洁的做法,开一个变量index,每次把正确的结果放到下标为index的位置上,index++,遍历完之后index就是目标数组的长度。

     1 /**
     2  * @param {number[]} nums
     3  * @return {number}
     4  */
     5 var removeDuplicates = function(nums) {
     6     var index = 0, i, previous, previous2;
     7     for(i = 0; i < nums.length; i++){
     8         if(nums[i] !== previous){
     9             nums[index++] = nums[i];
    10         }else if(nums[i] === previous && nums[i] !== previous2){
    11             nums[index++] = nums[i];
    12         }
    13         previous2 = previous;
    14         previous = nums[i];
    15     }
    16     return index;
    17 };
  • 相关阅读:
    Resharper进阶一
    脚本(js)控制页面输入
    IE图标消失 HTML文件图标变为未知图标的解决方法
    memcache_engine + memcachedb = 高性能分布式内存数据库
    sql 求差值
    MSN、QQ的网页链接代码
    IFrame语法:IFrame实例应用集
    Memcache协议
    Windows下的Memcache安装
    文本框 价格 保留两位小数 讨论
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4889808.html
Copyright © 2011-2022 走看看