删除有序数组中的重复项

Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

//nums is passed in by reference.(i.e, without making a copy)

int len = removeDuplicates(nums);

//any modification to nums in your function would be known by the caller.

//using the length returned by your function, it prints the first len elements.

for(int i = 0; i < len; i++) {

​ print(nums[i]);

}

在这里插入图片描述

今天的每日一题是一道简单难度的题目,要求是删除有序数组中的重复项(咦?怎么看起来这么眼熟?)看了一下,之前有做过一道类似的题目,也是有序数组元素的原地去重。只不过那个题目要求一个元素可以重复两次,而今天的题目是只能出现一次。但是这两道题的思路是一样的,定义快慢两个指针,快指针用来遍历输入数组,慢指针用来记录被保留的元素当前所处的位置。
删除有序数组中的重复项II

话不多说,直接上代码:

/**
 * @author: LittleWang
 * @date: 2021/4/18
 * @description:
 */
public class Solution {
    public int removeDuplicates(int[] nums) {
        int fast = 1, slow = 1;                 //因为数组的第一个元素一定会被保留,所以索引直接从1开始
        if(nums.length == 0 || nums.length == 1){   //判断特殊情况,输入数组长度为0或1时直接返回原数组
            return nums.length;
        }
        while(fast < nums.length) {
            if(nums[fast] != nums[fast-1]) {        //如果当前元素不重复,就把当前元素赋值给慢指针所指的位置,同时快慢指针+1
                nums[slow++] = nums[fast++];
            }
            else {                                  //否则慢指针不动,快指针继续向后遍历
                fast++;
            }
        }

        return slow;
    }
}

提交结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值