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;
        }
    };
  • 相关阅读:
    搭建elk的坑
    mail发邮件报错 "send-mail: fatal: parameter inet_interfaces: no local interface found for ::1"
    shell脚本排坑
    rocketmq双主发送消息 SLAVE_NOT_AVAILABLE 状态
    基于mysql的基准测试
    mysql服务器参数
    MySql Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' 解决方法
    mysql存储引擎
    zabbix安装
    iostat查看系统的IO负载情况
  • 原文地址:https://www.cnblogs.com/irun/p/4753484.html
Copyright © 2011-2022 走看看