Cracking coding interview(2.1)去除LinkedList中的重复元素

2.1 Write code to remove duplicates from an unsorted linked list.
FOLLOW UP

How would you solve this problem if a temporary buffer is not allowed?

import java.util.LinkedList;
import java.util.Iterator;
import java.util.Collections;
import java.util.Hashtable;

public class Solution{
	//brute-force time complexity:O(n^2) space complexity:O(1)
	public static void removeDuplicate1(LinkedList<Integer> list){
		for(int i=0;i < list.size()-1;i++)
			for(int j=i+1;j < list.size();)
				if(list.get(i) == list.get(j))
					list.remove(j);
				else
					j++;
	}
	//could't keep order time complexity:O(nlogn) space complexity:O(1)
	public static void removeDuplicate2(LinkedList<Integer> list){
		//sort
		Collections.sort(list);	
		if(list.size() >= 2){
			for(int i=0;i < list.size()-1;){
				if(list.get(i) == list.get(i+1))
					list.remove(i+1);
				else
					i++;
			}
		}		
	}
	//1.keep order 2.time complexity:O(n) 3.space complexity:O(n): (worst case)
	public static void removeDuplicate3(LinkedList<Integer> list){
		Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
		//lookup hashtable to delete repeat elements
		for(int i=0;i < list.size();){
			if(hash.containsKey(list.get(i)))
				list.remove(i);
			else{
				hash.put(list.get(i), "");
				i++;
			}
		}
	}
	private static void printLinkedList(LinkedList<Integer> list){
		Iterator it = list.iterator();
		while(it.hasNext()){
			System.out.print((Integer)it.next()+" ");
		}
		System.out.println();
	}
	public static void main(String[] args){
		LinkedList<Integer> list = new LinkedList<Integer>();	
		list.add(6);list.add(2);list.add(2);list.add(3);
		list.add(1);list.add(4);list.add(2);list.add(3);
		list.add(7);list.add(2);list.add(2);list.add(10);
		
		Solution.printLinkedList(list);
		Solution.removeDuplicate3(list);
		Solution.printLinkedList(list);
	}
}

1.brute-force time complexity: O(n^2) space complxity:O(1), 输出元素保持原有顺序

2.sort:time complexity:O(nlogn) space complexity:O(1), 输出元素为排序后结果

3.hashtable:time complexity:O(n) space complexity:O(n), 输出元素保持原有顺序

类似问题:http://blog.csdn.net/u011559205/article/details/38125405



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值