zoukankan      html  css  js  c++  java
  • leetcode 80 Remove Duplicates from Sorted Array II ----- java

    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.

    是第26题的延伸版,26题说的是给一个排序好的数组,然后删掉所有重复的数字,使所有数字只出现1次,然后返回长度。

    这道题指的是允许数字最多出现2次。然后求长度len2。并且返回的数组前len2个数应当是整理过之后的数组。

    public class Solution {
        public int removeDuplicates(int[] nums) {
    
            int len = nums.length;
            if( len < 2 )
                return len;
            int flag = nums[0];
            int times = 1;
            int res = len;
            for( int i = 1 , j = 1;i<len;i++){
                if( flag == nums[i] ){
                    if( times == 1)
                        times++;
                    else{
                        res--;
                        continue;
                    }
                }else{
                    flag = nums[i];
                    times = 1;
                }
                nums[j] = nums[i];
                j++;
            }
            
            return res;
        }
    }
  • 相关阅读:
    Python 基础之函数初识与函数参数
    python 基础之浅拷贝与深拷贝
    Python 基础之集合相关操作与函数和字典相关函数
    Python 基础之字符串操作,函数及格式化format
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5967229.html
Copyright © 2011-2022 走看看