Remove Duplicates from Sorted Array II

来源:互联网 发布:多功能网络表 编辑:程序博客网 时间:2024/06/17 02:25

Remove Duplicates from Sorted Array II


Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

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]

Java代码:

public class Solution {    public int removeDuplicates(int[] A) {    Integer prev = null; // last value    int count = 0; // number of continuous occurrences of last value    int index = 0; // points to index to place next qualified element    for (int i = 0; i < A.length; i++) {        int candidate = A[i];        if (prev != null && prev == candidate && count == 2)            continue;        A[index++] = A[i];        // reset count if a new value is encountered        if (prev == null || candidate != prev) {            prev = candidate;            count = 1;        } else            count++;    }    return index;}}

 

0 0
原创粉丝点击