【作业1】LeetCode 26. 删除有序数组中的重复项
对应课程链接:拿捏算法面试:6. LeetCode27.移除元素
这道题也是用双指针哦,和我们课程中讲解的那一道很像,可以当作练习题来做哦,作业要求:
1、给出 26. 删除有序数组中的重复项 运行通过的代码。
PS:如果你不知道怎么打卡,可以看这里:打卡细则
对应课程链接:拿捏算法面试:6. LeetCode27.移除元素
这道题也是用双指针哦,和我们课程中讲解的那一道很像,可以当作练习题来做哦,作业要求:
1、给出 26. 删除有序数组中的重复项 运行通过的代码。
PS:如果你不知道怎么打卡,可以看这里:打卡细则
共以下 35 个回答
count表示不重复的数字个数-1
class Solution {
public int removeDuplicates(int[] nums) {
if(nums null || nums.length < 1){
return 0;
}
if(nums.length 1){
return 1;
}
int l = 0;
int r = 1;
int count = 1;
while(r <= nums.length – 1){
if(nums[l] nums[r]){
r++;
}else{
nums[count] = nums[r];
count++;
l = r;
r++;
}
}
return count;
}
}
“`java
len指向当前的无重复数组的最后一个元素
打卡
打卡
class Solution {
public int removeDuplicates(int[] nums) {
if(nums null || nums.length < 1){
return 0;
}
int l = 0;
int r = 1;
while(r < nums.length){
if(nums[l] nums[r]){
r++;
}else{
l++;
nums[l] = nums[r];
r++;
}
}
return l+1;
}
}
时间复杂度O(n) 空间复杂度O(1) 原地比较与替换
快慢指针,一开始都在下标为1处,交换的条件是f的值和f-1不一样,交换完s++
打卡
class Solution {public int removeDuplicates(int[] nums) {
int left = 0;
int right = 0;
while (left <= right && right < nums.length) {
if (nums[left] == nums[right]) {
right++;
} else {
nums[++left] = nums[right];
}
}
return left + 1;
}
}
打卡
C++代码,用cnt记录多余的元素,依次遍历数组,判断当前元素、或者移动cnt个位置。
作业打卡
简化版双指针
时间复杂度O(n)
时间O(n) 空间O(1)
时间复杂度O(n)空间O(1)
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length 0){
return 0;
}
int slow = 0;
int fast = 0;
while(fast<nums.length){
if(nums[slow]!=nums[fast]){
slow++;
nums[slow] = nums[fast];
}
fast++;
}
return slow + 1;
}
}
可简化为:
双指针分别指示当前位置和数值交换位置
//双指针
双指针 时间复杂度O(n)
双指针加亦或操作
快慢指针
下面是代码
作业一打卡