LeetCode---26. Remove Duplicates from Sorted Array

##LeetCode—26. Remove Duplicates from Sorted Array

####题目
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
给出一个有序数组,要求将将其中重复的数挑出,只剩下不重复的数字,不能增加空间复杂度,,也就是不能新建数组,将不重复的数字排在原数组的前面,返回不重复数字的个数。例如:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.
Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

####思路及解法
要注意到,原数组是有序的,也即是重复的数字一定是相邻的。首先要循环遍历数组,找到重复的数字,每找到第一个不重复的数字,就要把这个数放到,数组的前面。我们维护两个指针,一个用来遍历原数组,一个记录新数字放置的位置。另外要注意端点的情况。

####代码

时间复杂度O(n)
空间复杂度O(1)
class Solution {
    public int removeDuplicates(int[] nums) {
        int len = nums.length;
        int j = 0;
        for(int i = 1 ; i < len ; i++){
            if(nums[i] != nums[i-1]){
                j++;
                nums[j] = nums[i];
            }
        }
        return j+1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值