首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >[LeetCode]Remove Duplicates from Sorted Array

[LeetCode]Remove Duplicates from Sorted Array

作者头像
全栈程序员站长
发布2022-07-08 18:53:25
发布2022-07-08 18:53:25
4140
举报

大家好,又见面了,我是全栈君。

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].

这道题是要求删除一个有序数组中的反复元素。

由于是有序数组,所以值同样的元素一定在连续的位置上,用相似于插入排序的思想。初始时将第一个元素看做是非反复的有序表。之后顺序依次推断后面的元素是不是比前面非反复有序数组的最后一个元素同样。若同样,则继续向后推断。若不同,则插入到前面的非反复有序数组的最后,直到推断到数组结束。

代码语言:javascript
复制
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(!n)
            return 0;
        int i=0,j=1;
        for(;j<n;j++){
            if(A[i]<A[j]){
                A[++i]=A[j];
            }
        }
        return i+1;
    }
};

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/116010.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年1月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档