In place with 2 pointers via Java


  • 0
    C

    Similar to removeDuplicationI, difference is we need an extra variable to remember the frequency of current value. If It is 1, we can insert the same element after it, otherwise we need to insert a new value after it.

    public class Solution {
        public int removeDuplicates(int[] A) {
            if (A == null) {
                return 0;
            }
            if (A.length <= 2) {
                return A.length;
            }
            int insert = 1, index = 1;
            int freq = 1;
            while (index < A.length) {
                if (A[index] == A[insert - 1] && freq == 1) {
                    A[insert] = A[index];
                    insert++;
                    freq++;
                }
                if (A[index] != A[insert - 1]) {
                    A[insert] = A[index];
                    insert++;
                    freq = 1;
                }
                index++;
            }
            return insert;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.