LeetCode的medium题集合(C++实现)十六
2015-05-29 11:08
645 查看
1 Remove Duplicates from Sorted Array II
Follow up for “Remove Duplicates”:What if duplicates are allowed at most twice?For example,Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
与删除重复的元素不同,这里只删除重复数超过2的部分。与删除重复的元素做法一样,只不过多用一个标记量flag记录重复的个数是否超过2.
2 Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.For example:
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
因为相同的元素全部被删除,则链表的第一个指针可能被删,因此必须要用到指向链表第一个节点的头指针。
Follow up for “Remove Duplicates”:What if duplicates are allowed at most twice?For example,Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
与删除重复的元素不同,这里只删除重复数超过2的部分。与删除重复的元素做法一样,只不过多用一个标记量flag记录重复的个数是否超过2.
[code]int removeDuplicates(vector<int>& nums) { int n=nums.size(); if(n==0) return 0; int length=0; bool flag=false; for(int i=1;i<n;i++) { if(nums[length]!=nums[i]) { nums[length+1]=nums[i]; length++; flag=false; } else { if(!flag) { flag=true; nums[length+1]=nums[i]; length++; } } } return length+1; }
2 Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.For example:
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
因为相同的元素全部被删除,则链表的第一个指针可能被删,因此必须要用到指向链表第一个节点的头指针。
[code] ListNode* deleteDuplicates(ListNode* head) { if(head==NULL) return NULL; ListNode* result=new ListNode(0); result->next=head; ListNode* pre=result; ListNode* cur=head; while(cur) { if(cur->next&&cur->val==cur->next->val) { int value=cur->val; while(cur->next&&value==cur->next->val) { //删除第一个元素以外的重复元素 ListNode* mid=cur->next; cur->next=mid->next; delete mid; } ListNode* t=cur; cur=t->next; delete t; //删除第一个重复元素 pre->next=cur; } else { pre=cur; cur=cur->next; } } return result->next; }
相关文章推荐
- OC与C++混编工程配置
- Android NDK学习 <五> C++ 支持
- C++ 8.1 面向对象的标准库(未完)
- c++中BOOL和bool的区别
- C++静态联编与动态联编
- 经典回溯算法——八后问题
- 趣味图形之 余弦函数cos与直线相交(另一种相交)
- C/C++之回调函数介绍
- 趣味图形之 余弦函数cos与直线相交
- 值得推荐的C/C++框架和库 (真的很强大)
- 趣味图形之 二次函数与圆相交
- C++指针--字符串与指针
- 趣味图形之 正弦函数sin&&余弦函数cos相交
- C++ 7.9 指向函数的指针
- C++学习 Boost状态机说明statechart
- C++读取系统当前时间
- C++读取系统当前时间 分类: C/C++ 2015-05-29 10:03 47人阅读 评论(0) 收藏
- c++中的继承、聚合、关联和组合
- [C语言] 对于scanf()函数使用%d格式说明符无法读取字符的个人理解
- C++类对应的内存结构