【LeetCode】026. Remove Duplicates from Sorted Array
2024-09-03 04:30:47
题目:
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 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.
题解:
感觉这个题是真没什么好解析的。。。
Solution 1()
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n < )
return n;
int index = ;
for(int i = ; i < n; ++i)
if(nums[index] != nums[i])
nums[++index] = nums[i];
return index + ;
}
};
Solution 2()
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
int count = ;
for(int i = ; i < n; i++){
if(A[i] == A[i-]) count++;
else A[i-count] = A[i];
}
return n-count;
}
};
Solution 3
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if (len <= ) {
return ;
}
int prev = , cur = ;
while (cur < len) {
if (nums[cur] == nums[prev]) {
++cur;
} else if (cur != prev + ){
nums[++prev] = nums[cur++];
} else {
++prev;
++cur;
}
}
return prev + ;
}
};
为了避免多余的复制操作,可以扩展使用,比如类数组,当数组没有重复对象时,无需复制操作。而之前的两个解答将会依次复制。
最新文章
- 转:详解Eclipse断点
- ROS语音交互——科大讯飞语音合成TTS(二)
- rabbitmq 相关方法
- Shared Library Search Paths
- c++ 全局变量初始化的一点总结
- [ERROR] Plugin &#39;InnoDB&#39; init function returned error
- 实现WMSservice的时候,出现边缘的点或icon被切断的情况
- 车牌识别LPR(八)-- 字符识别
- sql server where、group by、order by 执行顺序
- Gamit解算脚本
- 禁止chrome中CORS跨域资源共享错误
- ASP.Net中使用Report Service
- Java面试题精选(三) JSP/Servlet Java面试逻辑题
- 从零使用Python测试。Testing Using Python.
- [转载]binlog归档
- struts2简单入门-数据校验
- vue+vux页面滚动定位(支持上下滑动)
- Jenkins入门-环境搭建(1)
- js动态添加未知新属性
- hdu 2005 求第几天(水题)