zoukankan      html  css  js  c++  java
  • Remove Duplicates from Sorted Array II ——LeetCode

    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.

    题目大意:给定一个排好序的数组,有重复元素,要求返回新数组长度,新数组中重复元素只能出现两次,新长度后面的是什么无所谓。

    解题思路,从前向后遍历,记录一个newLen变量,重复元素记录两次,非重复元素就直接copy到新数组应有的下标处。

        public int removeDuplicates(int[] nums) {
            if(nums==null||nums.length==0){
                return 0;
            }
            int newLen=0;
            for(int i=0;i<nums.length;i++){
                int pos=i;
                nums[newLen++]=nums[i];
                while(i<nums.length-1&&nums[i]==nums[i+1]){
                    i++;
                }
                if(pos==i)
                    continue;
                nums[newLen++]=nums[i];
            }
            return newLen;
        }
  • 相关阅读:
    Oracle数据库的备份及恢复策略研讨
    ast入门 (一)
    DisableThreadLibraryCalls
    写入注册表实现自启动
    QT学习1 hello程序
    打印断言函数
    注册表基本知识
    RAS详解
    const
    QT安装
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4559083.html
Copyright © 2011-2022 走看看