Two Pointer로 구현
class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
if(nums.length == 0) return 0;
for (int j = i+1; j < nums.length; j++) {
if(nums[i] != nums[j]) {
i++;
nums[i] = nums[j];
}
}
return i+1;
}
}
O(N^2)
class Solution {
public int removeDuplicates(int[] nums) {
// The initial length is simply the capacity.
int length = nums.length;
// Assume the last element is always unique.
// Then for each element, delete it iff it is
// the same as the one after it. Use our deletion
// algorithm for deleting from any index.
for (int i = length - 2; i >= 0; i--) {
if (nums[i] == nums[i + 1]) {
// Delete the element at index i, using our standard
// deletion algorithm we learned.
for (int j = i + 1; j < length; j++) {
nums[j - 1] = nums[j];
}
// Reduce the length by 1.
length--;
}
}
// Return the new length.
return length;
}
}
'JAVA > leetcode' 카테고리의 다른 글
[LeetCode] Array - Valid Mountain Array (0) | 2021.08.05 |
---|---|
[LeetCode] Array - Check If N and Its Double Exist (0) | 2021.08.05 |
[LeetCode] Array - Remove Element !! (0) | 2021.08.05 |
[LeetCode] Array - Merge Sorted Array (0) | 2021.08.05 |
[LeetCode] Array - Duplicate Zeros !! (0) | 2021.08.05 |