Skip to content

Commit

Permalink
LC 26: Remove Duplicates from Sorted Array
Browse files Browse the repository at this point in the history
  • Loading branch information
IlyaMoskva committed Jan 24, 2024
1 parent 5ec5545 commit 0d6ce27
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.company.leetcode.numbers;

/**
LC 26: Remove Duplicates from Sorted Array
Given an integer array nums sorted in non-decreasing order,
remove the duplicates in-place such that each unique element appears only once.
The relative order of the elements should be kept the same.
Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k,
to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements
in the order they were present in nums initially.
The remaining elements of nums are not important as well as the size of nums.
Return k.
*/
public class RemoveDupesFromArray {
public int removeDuplicates(int[] nums) {
int cur = 1;
int next = 1;
while (next<nums.length) {
if (nums[next]==nums[cur-1]) next++;
else {
nums[cur] = nums[next];
cur++;
}
}
return cur;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.company.leetcode.numbers;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import static org.junit.jupiter.api.Assertions.*;

class RemoveDupesFromArrayTest {
public static Object[][] data() {
return new Object[][]{
new Object[]{2, new int[]{1,1,2}},
new Object[]{5, new int[]{0,0,1,1,1,2,2,3,3,4}}
};
}

@ParameterizedTest
@MethodSource("data")
public void removeDuplicatesTest(int expected, int[] given) {
assertEquals(expected, new RemoveDupesFromArray().removeDuplicates(given));
}

}

0 comments on commit 0d6ce27

Please sign in to comment.