O(n) solution with O(1) space in Java


  • 4
    C

    Two pointers. One denotes the position to insert an element which is different from previous values. Another iterates the array until the end. The length equals the index of last position needs to be inserted with a value.

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

Log in to reply
 

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