zoukankan      html  css  js  c++  java
  • Leetcode 80. 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.


    解题思路:

    Two pointers


    Java code 

    九章算法

    public class Solution {
        public int removeDuplicates(int[] nums) {
            if(nums == null || nums.length == 0) {
                return 0;
            }
            int cur = 0;
            int i, j;
            for(i = 0; i< nums.length;) {
                int now = nums[i];
                for(j = i; j < nums.length; j++) {
                    if(nums[j] != now){
                        break;
                    }
                    if(j - i < 2){
                        nums[cur++] = now;
                    }
                }
                i = j;
            }
            return cur;
        }
    }

    Reference:

    1. http://www.jiuzhang.com/solutions/remove-duplicates-from-sorted-array-ii/

  • 相关阅读:
    事务的隔离级别
    事务的隔离
    事务简介
    leetcode647
    leetcode394
    leetcode96
    leetcode814
    leetcode738
    leetcode621
    leetcode763
  • 原文地址:https://www.cnblogs.com/anne-vista/p/5140974.html
Copyright © 2011-2022 走看看