• [LeetCode-JAVA] 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.

    思路:记录每个数字的次数,并且维护新数组的位置。

    public class Solution {
        public int removeDuplicates(int[] nums) {
            if(nums.length == 0)
                return 0;
                
            int walker = 1; //每个的数量
            int count = 1; //总类数量
            int loc = 1; //定位
    
            for(int i = 1 ; i < nums.length ; i++){            
                if(nums[i] == nums[i-1]){
                    if(walker < 2){
                        walker++;
                        count++;
                    }else{    //出现次数大于2次
                        walker++;
                        continue;
                    }
                }else{
                        walker = 1;    //出现新数字
                        count++;
                }
                nums[loc] = nums[i];
                loc++;
            }
            
            return count;
        }
    }
  • 相关阅读:
    Django Ajax
    Django模板层
    Django session源码剖析
    CBV源码剖析
    Django视图层
    Django版本区别
    Django路由层
    Django高级
    Django ORM
    Django入门
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4510441.html
Copyright © 2020-2023  润新知