Home [Easy] Remove Duplicates from Sorted Array
Post
Cancel

[Easy] Remove Duplicates from Sorted Array

‘Remove Duplicates from Sorted Array’ in LeetCode (Easy)


📌 Problem

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

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int removeDuplicates(int[] nums) {
        int i = 0;
        
        for (int n : nums) {
            if (i == 0 || n > nums[i-1]) nums[i++] = n;
        }
        
        return i;
    }
}

The point

  • O(1) extra memory
    • Do not allocate extra space for another array.
  • return a array size that you modified
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public int removeDuplicates(int[] nums) {
        
        int j = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[j] != nums[i]) {
                j++;
                nums[j] = nums[i];
            }
        }
        
        return j + 1;
    }
}

Custom Judge

1
2
3
4
5
6
7
8
9
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
}
This post is licensed under CC BY 4.0 by the author.

[Spring] Apache Kafka + Spring Boot

[Java String methods] Implement strStr()

Comments powered by Disqus.