Remove Duplicates from Sorted Array

Problem: Remove Duplicates from Sorted Array

We use two pointers, one static and one dynamic. Dynamic one keeps going forward. If dynamic one scans a number different from what static one points to, we change that number with the number with the number after static pointer and move static one one step ahead. By this method, we can make sure non-duplicate numbers are located at leading part of array. And by the index the static pointer points to, we can easily return our answer.

Code in Python:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums: return 0
        i = 0
        for j in xrange(1, len(nums)):
            if nums[j] != nums[i]:
                nums[i+1], nums[j] = nums[j], nums[i+1]
                i += 1
        return i+1

Code in Java:

public class Solution {
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
        int res = n;

        if (n == 0 || n == 1)
            return n;

        int i = 0, j = 1;
        while (j < n) {
            if (nums[j] == nums[i]) {
                res--;
                j++;
            } else {
                i++;
                nums[i] = nums[j];
                j++;
            }
        }

        return res;
    }
}

results matching ""

    No results matching ""