把几个remove的问题放在一起,看来自己做的太不好了,明明很简单的问题做的很复杂
Remove Duplicates from Sorted Array
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n<=0) return 0;
if(n==1) return 1;
int i=0,j=1;
//遍历一遍有相同的就用后面的元素覆盖
while(j<n)
{
if(A[j] == A[i])
++ j;//因为是数组不好一次次挪元素,所以是遇到不同的再挪,同的往后走,这样对总体只能了一次
else
A[++i] = A[j++];
}
return i+1;
}
};
Remove Duplicates from Sorted Array II
保留相同的两个元素,多余的删去
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n==0 || n==1 || n==2) return n;
int i=0,j=1;
bool flag = false;
while(j<n)
{
if(!flag && A[j] == A[i])//flag是true表示已经有两个相同的
{
flag = true;
++i;
A[i] = A[j];//没想到这一步,就是将后一个相同的元素移动到i的后面,覆盖之前的元素
}
else if(A[j] != A[i])
{
flag = false;
++ i;
A[i] = A[j];//不同的元素挪动到前面,并且置flag为false
}
++j;
}
return i+1;
}
};
Remove Duplicates from Sorted List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL || head->next == NULL) return head;
ListNode* p= head;
ListNode* q= head->next;
while(q != NULL)
{
if(q->val == p->val)
{
p->next = q->next;
delete q;//一遇到相同就用后面的元素覆盖因为是链表,记得删去不用的节点免得内存溢出
}
else
{
p = p->next;//不同怎往后走
}
q = p->next;//总是让q是p的下一个
}
return head;
}
};
Remove Duplicates from Sorted List II
只要是重复的都删去
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* guard = new ListNode(0);//利用一个节点指向head,简化了对head处理问题
guard->next = head;
ListNode* p =guard;//p一开始是指向guard的
ListNode* q = head;
ListNode* temp =NULL;
while(q!=NULL && q->next!=NULL)//需要先判断q再q->next
{
if(q->next->val != q->val)//不相同就一起移动,p记录不同节点对中前一个节点
{
p = q;
q = q->next;
}
else
{
while(q->next!=NULL && q->val == q->next->val)//相同,就让q一直移动,直到与后面的不同时跳出
{
temp = q->next;
delete q;
q=temp;
}
p->next=q->next;//因为所有重复删去,p记录是与q首次不同点,q-next是下一次不同点,连接
delete q;
q=p->next;
}
}
return guard->next;
}
};
Remove Nth Node From End of List
删除倒数第n个节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head == NULL) return head;
if(head->next == NULL && n==1) return NULL;
ListNode* guard = new ListNode(0);
guard->next = head;
ListNode* k = guard;
ListNode* p = guard;
ListNode* q = guard;
int i=0;
for(i=0;i<n;++i)
k = k->next;
while(k!=NULL)
{
p=q;
q=q->next;
k=k->next;
}
p->next = q->next;
delete q;
return guard->next;
}
};
Remove Element
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int i = 0, s = 0;
while(s<n)
{
while(s < n && A[s] == elem)
++ s;
if(s<n)
A[i++] = A[s++];
}
return i;
}
};