博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Remove Duplicates from Sorted Array--从有序数组中移除重复元素
阅读量:4106 次
发布时间:2019-05-25

本文共 783 字,大约阅读时间需要 2 分钟。

问题:

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 in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

解答:

两个指针,first指向最后一个非重复元素,last指向未处理的元素的第一位,两个指针都初始化为0。

代码:

class Solution {public:    int removeDuplicates(int A[], int n) {        int first,last;        first = last = 0;        if(n == 0)            return 0;        while(last != n)        {            if(A[first] == A[last])            {                ++last;            }            else            {                A[first+1] = A[last++];				++first;            }        }        return first+1;    }};

转载地址:http://tktsi.baihongyu.com/

你可能感兴趣的文章
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
谷歌阅读器将于2013年7月1日停止服务,博客订阅转移到邮箱
查看>>
浅谈JavaScript的语言特性
查看>>
Lua解释器
查看>>
Notepad++ 16进制编辑功能
查看>>
N沟道增强型MOS管双向低频开关电路
查看>>
VS2010点滴——不能将参数 1 从“const char [11]”转换为“LPCWSTR”
查看>>
error C2065: “CString”: 未声明的标识符
查看>>
Building MFC application with /MD[d] (CRT dll version)requires MFC shared dll version~~~~
查看>>
error C2668: “pow”: 对重载函数的调用不明确
查看>>
详解C语言字节对齐
查看>>
Long Long、__int64使用总结
查看>>
c语言内存分配函数
查看>>
c语言内存分配函数之间的区别
查看>>
二维数组和指针的一些感悟
查看>>
二维数组和二级指针
查看>>
VC让对话框显示就最大化
查看>>
Unicode和多字节字符集 (MBCS) 杂谈
查看>>
MFC中char*,string和CString之间的转换
查看>>
COMMTIMEOUTS详解
查看>>