博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Remove Element--原地移除重复元素
阅读量:4106 次
发布时间:2019-05-25

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

问题:

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

解答:

先排序,后设定两个指针,first指向第一个等于elem的位置,last指向first之后,第一个不等于elem的元素。

first和last之间就是重复的元素elem。

重点注意:

1 因为第一步是寻找数组中等于elem的第一个位置,如果数组中没有该元素,需要特别的处理。

2 如果输入的数组大小为0,直接返回0.

  

代码:

class Solution {public:    int removeElement(int A[], int n, int elem) {		if(n == 0)			return 0;        sort(A, A+n);        int first,last;        first = 0;        while(A[first] != elem)        {            ++first;            if(first == n)                return n;        }                last = first;        while(A[last] == elem)            ++last;        while(last != n)            A[first++] = A[last++];        return n - (last - first);    }};

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

你可能感兴趣的文章
collect2: ld returned 1 exit status
查看>>
C#入门
查看>>
查找最大值最小值
查看>>
杨辉三角
查看>>
冒泡排序法
查看>>
C#中ColorDialog需点两次确定才会退出的问题
查看>>
16、Memento 备忘录模式
查看>>
Java基础篇(一)
查看>>
数据库
查看>>
mysql update与group by
查看>>
nginx反代 499 502 bad gateway 和timeout
查看>>
linux虚拟机安装tar.gz版jdk步骤详解
查看>>
python猜拳游戏
查看>>
python实现100以内自然数之和,偶数之和
查看>>
python数字逆序输出及多个print输出在同一行
查看>>
ESP8266 WIFI数传 Pixhaw折腾笔记
查看>>
苏宁产品经理面经
查看>>
百度产品经理群面
查看>>
去哪儿一面+平安科技二面+hr面+贝贝一面+二面产品面经
查看>>
element ui 弹窗在IE11中关闭时闪现问题修复
查看>>