您的位置:首页 > 其它

【LeetCode】Remove Duplicates from Sorted List 解题报告

2016-05-01 15:06 417 查看

Remove Duplicates from Sorted List

[LeetCode]

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Total Accepted: 114584 Total Submissions: 311665 Difficulty: Easy

Question

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.

Ways

方法一

我的方法。嗯。比较智障。用了两个指针。一个指向现在正在看的这个元素叫做move,另一个指向后面的元素叫做next,每次比较move时,一次性的找出后面有几个和move相同的元素让next查找出来,让move跳过去。

确实智障。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return head;
}
ListNode next;
ListNode move=head;
while(move!=null&&move.next!=null){
next=move.next;
while(next!=null && move.val==next.val){
next=next.next;
}
move.next=next;
move=next;
}

return head;

}
}


AC:2ms

方法二

LeetCode官方解答。

如果下一个元素和这个元素的值相等。这个元素的下个元素就等于下个元素的下个元素。再循环就好了。相当于只要下个跟我的相等,我就跳过你。

在找到不同的元素之前,当前元素不走。找到之后再走。

This is a simple problem that merely tests your ability to manipulate list node pointers. Because the input list is sorted, we can determine if a node is a duplicate by comparing its value to the node after it in the list. If it is a duplicate, we change the next pointer of the current node so that it skips the next node and points directly to the one after the next node.

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode move=head;
while(move!=null && move.next!=null){
if(move.next.val == move.val){
move.next=move.next.next;
}else{
move=move.next;
}
}

return head;

}
}


Date

2016/5/1 15:05:24
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode