【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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解