LeetCode 26. Remove Duplicates from Sorted Array(移除有序数组的重复元素)

题目描述:

    Given a sorted array, remove the duplicates in-place such that each element appear only once and return 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.

例子:

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 new length.

分析:
    题意:给定一个有序数组,移除重复元素,使得每种元素只出现一次,并且返回新的数组长度。空间复杂度要求为O(1)。
    思路:此题采用双指针法。我们先初始化指针left=0、right=1,并且用cnt表示每个不重复元素在数组中的新位置,初始化为1。我们先查找第一个和指针left指向元素不同的元素位置,用指针right指向它,更新该元素到cnt位置,cnt加一,然后继续重复该操作(把指针right的值赋给指针left,指针right加一),直到更新完成所有元素。cnt的最终值就是新数组的长度。
    假设原数组总共有n个元素,那么时间复杂度为O(n),空间复杂度为O(1)。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int n = nums.size();
		// Exceptional Case: 
		if(n <= 1){
			return n;
		}
		int left = 0, right = 1, cnt = 1;
		while(right <= n - 1){
			while(right <= n - 1 && nums[left] == nums[right]){
				right++;
			}
			if(right <= n - 1){
				nums[cnt++] = nums[right];
				left = right;
				right = left + 1;
			}
		}
		return cnt;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值