LeetCode官网题目地址:力扣
Java实现代码:
package array;
/**
* @ClassName LeetCode 80.删除有序数组中的重复项 II
* @Description https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/
* @Author Jiangnan Cui
* @Date 2022/10/30 17:20
* @Version 1.0
*/
public class LeetCode80 {
/**
* @MethodName removeDuplicates
* @Description 方法2:快慢指针 for循环实现
* 时间复杂度:O(n)
* 空间复杂度:O(1)
* 满足题目要求
* 参考链接:https://www.bilibili.com/video/BV1By4y1b7q6
* @param: nums
* @return: int
* @Author Jiangnan Cui
* @Date 20:35 2022/10/30
*/
public int removeDuplicates(int[] nums) {
// 数组长度小于3时直接返回
if(nums.length < 3){
return nums.length;
}
// 其它情况下进行下面操作
// 慢指针用来改变元素位置
int left = 2;
// 快指针用来遍历元素
for (int right = 2; right < nums.length; right++) {
// 判断当前遍历元素和保存有效元素的前前位置的元素是否相等
if(nums[right] != nums[left - 2]){
// 不相等时进行元素替换,同时left加1右移
nums[left++] = nums[right];
}
// 相等时不做任何操作
}
// 最后left元素的大小即为有效数组的长度
return left;
}
/**
* @MethodName removeDuplicates2
* @Description 方法2:快慢指针 while循环实现
* 时间复杂度:O(n)
* 空间复杂度:O(1)
* 满足题目要求
* @param: nums
* @return: int
* @Author Jiangnan Cui
* @Date 20:35 2022/10/30
*/
public int removeDuplicates2(int[] nums) {
// 数组长度小于3时直接返回
if(nums.length < 3){
return nums.length;
}
// 其它情况下进行下面操作
// 慢指针用来改变元素位置
int left = 2;
// 快指针用来遍历元素
int right = 2;
while(right < nums.length){
// 判断当前遍历元素和保存有效元素的前前位置的元素是否相等
if(nums[right] != nums[left - 2]){
// 不相等时进行元素替换,同时left加1右移
nums[left++] = nums[right];
}
// 相等时不做任何操作
right++;
}
// 最后left元素的大小即为有效数组的长度
return left;
}
public static void main(String[] args) {
int[] nums = new int[]{1,1,1,2,2,3};
int i = new LeetCode80().removeDuplicates(nums);
System.out.println("i = " + i);
int[] nums2 = new int[]{1,1,1,2,2,3};
int i2 = new LeetCode80().removeDuplicates2(nums2);
System.out.println("i2 = " + i2);
int[] nums3 = new int[]{0,0,1,1,1,1,2,3,3};
int i3 = new LeetCode80().removeDuplicates(nums3);
System.out.println("i3 = " + i3);
int[] nums4 = new int[]{0,0,1,1,1,1,2,3,3};
int i4 = new LeetCode80().removeDuplicates2(nums4);
System.out.println("i4 = " + i4);
}
}
输出结果:
i = 5 i2 = 5 i3 = 7 i4 = 7
博客给出了LeetCode官网题目地址,还展示了Java实现代码及输出结果,聚焦于用Java解决LeetCode题目。
1657

被折叠的 条评论
为什么被折叠?



