Skip to content

Latest commit

 

History

History
44 lines (28 loc) · 619 Bytes

File metadata and controls

44 lines (28 loc) · 619 Bytes

Remove Duplicates from Sorted Array

Problem Link

https://leetcode.com/problems/remove-duplicates-from-sorted-array/


Pattern

  • Two Pointer

Approach

Use two pointers: one for the place to write unique elements, the other to scan.


Time Complexity

O(n)

Space Complexity

O(1)


Java Solution

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int idx = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[idx]) nums[++idx] = nums[i];
        }
        return idx + 1;
    }
}