26. Remove Duplicates from Sorted Array
来源:互联网 发布:苹果应用下载软件 编辑:程序博客网 时间:2024/05/16 15:57
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.
Subscribe to see which companies asked this question.
先翻译题目:移除给定有序数组中的重复元素,然后返回数组长度;不可额外创建数组,只允许使用当前数组空间;
我的思路是设置两个游标,i=0,j=1;因为这是一个有序数组,所以必定后面的元素大于或者等于前面的元素;
然后从j=1与i=0相比较,如果相等则j++,又与i=0相比较,直到不等为止,然后i++,将此时的j对应的元素赋值给i;
由于最后i指向的是最后一个元素的位置,所以数组长度还需要加一,i++,返回;
这里做的时候一开始没考虑如果是个空数组怎样,所以后来加上了对空数组的判断;
以下为代码示例:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0)
return 0;
int i=0;
int j=1;
for(j=1;j<nums.size();j++){
if(nums[i]==nums[j]){
continue;
}
i++;
nums[i]=nums[j];
}
i++;
return i;
}
};
- [LeetCode]26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode --- 26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- [Leetcode] 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 【leetcode】26. Remove Duplicates from Sorted Array
- 【leetcode】 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- [leetCode]26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array LeetCode
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 在半个中国象棋棋盘上,马在左下角(1,1)处,马走日字,求到指定位置有多少种走法
- PAT甲级1014. Waiting in Line (30)
- MPEG-2 TS学习(六)tsfilter源码阅读(3)TS的解析流程
- C++ 实现反射(一)
- 彼岸书店小览
- 26. Remove Duplicates from Sorted Array
- 274. H-Index
- Android 中为RecyclerView控件添加分隔线
- XML和JSON分别是什么?JSON有什么好处?
- 安卓开发学习心得-------Http访问时保持同一Session
- ResultSet相关ResultSetMetaData详细
- Probabilistic Frame-Semantic Parsing 论文阅读
- executeQuery、executeUpdate和execute
- servlet的工作原理