Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e547fc1

Browse files
add a solution for 26
1 parent fbffcce commit e547fc1

File tree

2 files changed

+39
-11
lines changed

2 files changed

+39
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,43 @@
11
package com.fishercoder.solutions;
22

3+
import com.fishercoder.common.utils.CommonUtils;
4+
35
public class _26 {
46

5-
public static class Solution1 {
6-
/**Key: It doesn't matter what you leave beyond the returned length.*/
7-
public int removeDuplicates(int[] nums) {
8-
int i = 0;
9-
for (int j = 1; j < nums.length; j++) {
10-
if (nums[i] != nums[j]) {
11-
i++;
12-
nums[i] = nums[j];
7+
public static class Solution1 {
8+
/**
9+
* Key: It doesn't matter what you leave beyond the returned length.
10+
*/
11+
public int removeDuplicates(int[] nums) {
12+
int i = 0;
13+
for (int j = 1; j < nums.length; j++) {
14+
if (nums[i] != nums[j]) {
15+
i++;
16+
nums[i] = nums[j];
17+
}
18+
}
19+
return i + 1;
1320
}
14-
}
15-
return i + 1;
1621
}
17-
}
22+
23+
public static class Solution2 {
24+
/**
25+
* My completely original solution on 2/2/2022.
26+
*/
27+
public int removeDuplicates(int[] nums) {
28+
int left = 0;
29+
int right = 1;
30+
for (; right < nums.length; right++) {
31+
while (right < nums.length && nums[right] == nums[right - 1]) {
32+
right++;
33+
}
34+
if (right < nums.length) {
35+
nums[++left] = nums[right];
36+
}
37+
}
38+
CommonUtils.printArray(nums);
39+
return left + 1;
40+
}
41+
}
42+
1843
}

src/test/java/com/fishercoder/_26Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,20 @@
88

99
public class _26Test {
1010
private static _26.Solution1 solution1;
11+
private static _26.Solution2 solution2;
1112
private static int[] nums;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _26.Solution1();
17+
solution2 = new _26.Solution2();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
nums = new int[]{1, 1, 2};
2123
assertEquals(2, solution1.removeDuplicates(nums));
24+
assertEquals(2, solution2.removeDuplicates(nums));
2225
}
2326

2427
@Test

0 commit comments

Comments
 (0)