leetCode-数组:Remove Duplicates from Sorted Array

Posted 机器爱学习

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetCode-数组:Remove Duplicates from Sorted Array相关的知识,希望对你有一定的参考价值。

 

Remove Duplicates from Sorted Array:从排列后的数组中删除重复元素

考察数组的基本操作:

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums==null || nums.length==0)
            return 0;
        int index = 1;
        for(int i =1; i<nums.length; i++){
            if(nums[i]!=nums[i-1]){
                nums[index] = nums[i];
                index++;
            }
        }
        return index;
    }
    public static void main(String[] args) {
      int[] arr = { 1, 2, 2, 3, 3 };
      arr = removeDuplicates(arr);
      System.out.println(arr.length);
}
}

Remove Duplicates from Sorted Array II (Java)

For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A is now [1,1,2,2,3].

最多允许两个重复,输出结果数组。

解法1:当counter是2时,就直接跳过即可,否则说明元素出现次数没有超,继续放入结果数组,若遇到新元素则重置counter。总体算法只需要扫描一次数组,所以时间上是O(n),空间上只需要维护一个index和counter,所以是O(1)。

public int removeDuplicates(int[] A) {
    if(A==null || A.length==0)
        return 0;
    int idx = 0;
    int count = 0;
    for(int i=1;i<A.length;i++)
    {
        if(A[i]==A[i-1])
        {
            count++;
            if(count>=3)
                continue;
        }
        else
        {
            count = 1;
        }
        A[idx++]=A[i];
    }
    return idx;
}

 解法二:

public class Solution {
    public int removeDuplicates(int[] A) {
        if (A.length <= 2)
            return A.length;
 
        int prev = 1; // point to previous
        int curr = 2; // point to current
 
        while (curr < A.length) {
            if (A[curr] == A[prev] && A[curr] == A[prev - 1]) {
                curr++;
            } else {
                prev++;
                A[prev] = A[curr];
                curr++;
            }
        }
 
        return prev + 1;
    }
}

 

以上是关于leetCode-数组:Remove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

leetcode26. Remove Duplicates from Sorted Array

leetCode-数组:Remove Duplicates from Sorted Array

LeetCode #316 Remove-Duplicate Letters 数组 字符串

leetcode#27 Remove Element

leetcode 27.Remove Element

[LeetCode] 26. Remove Duplicates from Sorted Array ☆(从有序数组中删除重复项)