1、Remove Duplecates from Sorted Array
题目要求:
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.
解题思路:题目中要求不能分配额外的数组空间,因此,我们只能借助原来的数组删除重复的元素,
代码如下:
2、Remove Duplicates from Sorted List
题目要求:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
解题思路:将后一个节点值与前一个节点值进行比较,如果相等,则删除
代码如下: