Java,用Map记录,然后重新建链表

删除有序链表中重复出现的元素

http://www.nowcoder.com/questionTerminal/71cef9f8b5564579bf7ed93fbe0b2024

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        ArrayList<Integer>res=new ArrayList<>();
        Map<Integer,Integer> map=new HashMap<>();
        ListNode cur=head;
        while(cur!=null){
            if(map.containsKey(cur.val)){
                map.put(cur.val,(int)map.get(cur.val)+1);
            }else{
                map.put(cur.val,1);
            }
            cur=cur.next;
        }
        for(Object i:map.keySet()){
            if((int)map.get(i)==1){
                res.add((int)i);
            }
        }
        int i=0;
        ListNode first=new ListNode(0);
        ListNode tt=first;
        Collections.sort(res);
        while(i<res.size()){
            ListNode temp=new ListNode((int)res.get(i));
            tt.next=temp;
            tt=temp;
            i++;
        }
        return first.next;
    }
}
全部评论

相关推荐

05-12 16:04
已编辑
江西财经大学 Java
点赞 评论 收藏
分享
04-29 22:35
门头沟学院 Java
牛友说改了名字能收到offer:旧图新发查看图片
点赞 评论 收藏
分享
大佬们,在大厂实习的都是几百一天???
哈尔滨的移动城堡_:那几个有名的大厂都是300-400,小厂有更高的
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务