zoukankan      html  css  js  c++  java
  • 83. Remove Duplicates from Sorted List【easy】

    83. Remove Duplicates from Sorted List【easy】

    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.

    解法一:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* deleteDuplicates(ListNode* head) {
    12         if (head == NULL || head->next == NULL) {
    13             return head;
    14         }
    15         
    16         ListNode * dummy = new ListNode(INT_MIN);
    17         dummy->next = head;
    18         
    19         while (head != NULL && head->next != NULL) {
    20             if (head->val == head->next->val) {
    21                 ListNode * temp = head->next;
    22                 head->next = temp->next;
    23                 free(temp);
    24             }
    25             else {          
    26                 head = head->next;                
    27             }
    28         }
    29         
    30         return dummy->next;
    31     }
    32 };

    这里也可以不用dummy节点,之所以那么写就是为了好看而已,嘿嘿

    解法二:

    1 public ListNode deleteDuplicates(ListNode head) {
    2         if(head == null || head.next == null)return head;
    3         head.next = deleteDuplicates(head.next);
    4         return head.val == head.next.val ? head.next : head;
    5 }

    参考了@wen587sort 的代码,大神的代码也是受到了下面的提示:

    This solution is inspired by renzid https://leetcode.com/discuss/33043/3-line-recursive-solution

    题外话,关于递归,我觉得@ElayMarco 的说法很中立:

    Well, on sites like these one's, I believe a lot of times people want to post 'other ways' of doing things, which is good. Recursive solutions sometimes require less coding to implement, and as a by-product of this look more clever or elegant. Recursion is just a tool. Sometimes the job calls for a hammer. Other times, a hammer is not suitable. Part of being a good programmer is knowing when to use which tools. But on sites like these, some people like to 'sharpen their tools' by writing recursive solutions to problems where iterative solutions are more efficient. Think of it as practice.

    看来,还是我自己太菜了……

  • 相关阅读:
    C#中的取整函数
    java代码(8) ---guava字符串工具
    java代码(7) ---guava之Bimap
    java代码(6) ---guava之multimap
    java代码(5) ---guava之Multiset
    java代码(4)---guava之Immutable(不可变)集合
    java代码(2)---Java8 Stream
    java代码(3)----guava复写Object常用方法
    java代码(1)---Java8 Lambda
    看完这篇HTTP,跟面试官扯皮就没问题了(转)
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7666929.html
Copyright © 2011-2022 走看看