JAVA/leetcode
[LeetCode] Array - Remove Duplicates from Sorted Array !!
JJunDol2
2021. 8. 5. 18:03
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;
}
}