zoukankan      html  css  js  c++  java
  • 【LeetCode】82

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    Failed solution : 不同于Remove Duplicates from Sorted List,II需要删除所有重复出现的节点,尝试过同时比较三个数,没有成功;

    Solution 1:runtime 12ms

    设置一个新的头节点newhead,比较newhead->next->val与cur->next->val,就变成了比较旧的头节点和第二个节点,直到找到与头节点val不等的节点,将newhead的next指向cur的next;如果cur==newhead->next, 则newhead移向下一个,

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(!head || !head->next )return head;
            ListNode *newhead=new ListNode(-1);
            newhead->next=head;
            ListNode *cur=head, *pre=newhead;
            while(cur){
                while(cur->next && pre->next->val==cur->next->val){
                    cur=cur->next;
                }
                if(cur==pre->next)
                    pre=pre->next;
                else
                    pre->next=cur->next;
                cur=cur->next;
            }
            return newhead->next;
        }
    };

     Solution 2:runtime 8ms

     设置一个temp变量记录重复节点的val, 删除所有val==temp的节点

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
         ListNode* deleteDuplicates(ListNode* head) {
            if(!head||!head->next)return head;
            ListNode *newhead=new ListNode(-1);
            ListNode *pre=newhead;
            int tmp;
            while(head && head->next){
              if(head->val!=head->next->val){
                  pre->next=head;
                  pre=pre->next;
                  head=head->next;
              }
              else{
                  tmp=head->val;
                  while(head&&tmp==head->val)head=head->next;
              }
            }
            pre->next=head;
            return newhead->next;
        }
    };
  • 相关阅读:
    Codeforces 845E Fire in the City 线段树
    Codeforces 542D Superhero's Job dp (看题解)
    Codeforces 797F Mice and Holes dp
    Codeforces 408D Parcels dp (看题解)
    Codeforces 464D World of Darkraft
    Codeforces 215E Periodical Numbers 容斥原理
    Codeforces 285E Positions in Permutations dp + 容斥原理
    Codeforces 875E Delivery Club dp
    Codeforces 888F Connecting Vertices 区间dp (看题解)
    Codeforces 946F Fibonacci String Subsequences dp (看题解)
  • 原文地址:https://www.cnblogs.com/irun/p/4753484.html
Copyright © 2011-2022 走看看