我最近在做一些leetcode习题,为了让自己在日常工作中思维更加敏捷。我会把自己的解法和别人的优良解法都列出来,以供自己学习和参考。
这是leetcode第83题:https://leetcode.com/problems/remove-duplicates-from-sorted-list/submissions/
我的解法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode pre = head;
while(pre != null && pre.next != null){
if(pre.val == pre.next.val){
pre.next = pre.next.next;
} else {
pre = pre.next;
}
}
return head;
}
}
Runtime: 1 ms, faster than 40.48% of Java online submissions for Remove Duplicates from Sorted List.
Memory Usage: 36 MB, less than 99.97% of Java online submissions for Remove Duplicates from Sorted List.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {//递归思想
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List.
Memory Usage: 36.1 MB, less than 99.97% of Java online submissions for Remove Duplicates from Sorted List.