问题描述:
给定一个有序数组,删除重复的地方,使每个元素只出现一次并返回新的长度。
(不要为其他数组分配额外的空间,您必须使用常量内存来完成此操作。)
例如,
给定输入数组A = [1,1,2],
你的函数应该返回length = 2,现在A是[1,2]。
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(A==NULL||n<=1)
return n;
int count=1;
for(int i=1;i<n;i++){
if(A[i]!=A[i-1]){
A[count++]=A[i];
}
}
return count;
}
};
相似问题:
去除单链表中重复的数
题目描述
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.
lass Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL||head->next==NULL) return head;
ListNode *p=head;
ListNode *q;
while(p->next&&p){
q=p->next;
if(q->val!=p->val){//不相等直接右移
p=p->next;
q=p->next;
}
else{
p->next=q->next;//相等则跳过该重复节点
}
}
return head;
}
};