LeetCode-Remove Duplicates from Sorted List II

来源:互联网 发布:java 浏览器 编辑:程序博客网 时间:2024/05/23 13:48
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/24017313
时间:2014-4-18

题目

Remove Duplicates from Sorted List II

 Total Accepted: 9519 Total Submissions: 38686My Submissions

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.

 Definition for singly-linked list. public class ListNode {     int val;     ListNode next;     ListNode(int x) {         val = x;         next = null;     } }

解法
几个不同想法:
  1. 用循环列表来删除
  2. 先扫描一遍记住要删除的元素,然后再扫一遍删除
解释:这两个方法前一个行不通,因为不是去重而是删去重复的所有数字,故基于频率的循环删除不可以。后者太麻烦,虽然可能只用一个指针解决问题,但是要多一次循环并且需要更多的空间。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head==null||head.next==null)            return head;        ListNode p = head;        ListNode dummy = new ListNode(Integer.MIN_VALUE);        ListNode pre = dummy;        int del = Integer.MIN_VALUE;                while(p!=null&&p.next!=null){            if(p.val == p.next.val){               del = p.val;               while(p.val == del){                    p=p.next;                    if(p==null)                        return dummy.next;               }            }            else{                pre.next = p;                pre = pre.next;                p=p.next;                pre.next = null;            }        }                    pre.next = p;                return dummy.next;    }}


返回

LeetCode Solution(持续更新,java>c++)

0 0
原创粉丝点击