Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list
题目原文:
Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items uniformly at random. Your algorithm should consume a logarithmic (or constant) amount of extra memory and run in time proportional to nlogn in the worst case.
分析:
此题要求对单向链表进行随机排序,可以考虑先实现个链表的归并排序(见我的另一篇文章),再改造成这里的随机排序。
import java.util.Iterator;
import edu.princeton.cs.algs4.StdRandom;
/**
/**
* 对单向链表的随机归并排序
* @author evasean www.cnblogs.com/evasean/
* @param <T>
*/
public class ShuffleLinkedList<T extends Comparable<T>> implements Iterable<T>{
private Node first = null;
private Node last = null;
private int n;
private class Node{
T element;
Node next;
}
private boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return new ListIterator();
}
private class ListIterator implements Iterator<T>{
private Node current = first;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return current != null;
} @Override
public T next() {
// TODO Auto-generated method stub
T t = current.element;
current = current.next;
return t;
}
}
public void add(T t){
Node node = new Node();
node.element = t;
node.next = null;
if(first == null && last == null){
first = node;
last = node;
}else if(first != null && first == last){
first.next = node;
last = node;
}else{
last.next = node;
last = node;
}
n++;
}
@Override
public String toString(){
Iterator<T> iter = iterator();
String ret = iter.next().toString();
while(iter.hasNext()){
ret += ", "+ iter.next().toString() ;
}
return ret;
}
public void mergeSort(){
first = sort(first);
} private Node sort(Node head){
if(head == null || head.next == null) return head;
Node slow = head;
Node fast = head;
//取中间节点
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
Node left = head;
Node right = slow.next;
slow.next = null; //将左右链表分开
left = sort(left);
right = sort(right);
return merge(left,right);
}
private Node merge(Node left, Node right){
//System.out.println("left="+left.element+",right="+right.element);
Node aux = new Node(); //需要耗费logn的额外空间
Node l= left;
Node r = right;
Node current = aux;
while(l != null && r!=null){
int rand = StdRandom.uniform(2);
if(rand == 0){ //如果随机数选为0,则从左侧选取元素
current.next = l;
current = current.next;
l= l.next;
}else{ //如果随机数选为1,则从右侧选取元素
current.next = r;
current = current.next;
r = r.next;
}
}
if(l!=null) current.next = l; // 如果左侧没遍历完,将其连接至current后
else if(r != null) current.next = r; //如果右侧没遍历完,将其连接至current后
return aux.next; //返回归并好的链表
}
public static void main(String[] args){
ShuffleLinkedList<Integer> sll = new ShuffleLinkedList<Integer>();
sll.add(1);
sll.add(2);
sll.add(11);
sll.add(9);
sll.add(10);
sll.add(4);
sll.add(7);
System.out.println(sll);
sll.mergeSort();
System.out.println(sll);
} }
Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list的更多相关文章
- Coursera Algorithms week3 归并排序 练习测验: Counting inversions
题目原文: An inversion in an array a[] is a pair of entries a[i] and a[j] such that i<j but a[i]>a ...
- Coursera Algorithms week3 归并排序 练习测验: Merging with smaller auxiliary array
题目原文: Suppose that the subarray a[0] to a[n-1] is sorted and the subarray a[n] to a[2*n-1] is sorted ...
- Coursera Algorithms week3 快速排序 练习测验: Selection in two sorted arrays(从两个有序数组中寻找第K大元素)
题目原文 Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respec ...
- Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)
题目原文: Decimal dominants. Given an array with n keys, design an algorithm to find all values that occ ...
- Coursera Algorithms week3 快速排序 练习测验: Nuts and bolts
题目原文: Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is t ...
- Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题
题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...
- Coursera Algorithms week1 算法分析 练习测验: 3Sum in quadratic time
题目要求: Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case ...
- Coursera Algorithms week2 基础排序 练习测验: Dutch national flag 荷兰国旗问题算法
第二周课程的Elementray Sorts部分练习测验Interview Questions的第3题荷兰国旗问题很有意思.题目的原文描述如下: Dutch national flag. Given ...
- Coursera Algorithms week4 基础标签表 练习测验:Inorder traversal with constant extra space
题目原文: Design an algorithm to perform an inorder traversal of a binary search tree using only a const ...
随机推荐
- [Windows Server 2012] IIS自带FTP配置方法
★ 欢迎来到[护卫神·V课堂],网站地址:http://v.huweishen.com★ 护卫神·V课堂 是护卫神旗下专业提供服务器教学视频的网站,每周更新视频.★ 本节我们将带领大家:IIS自带FT ...
- 更改计算机名后DB2不能启动的解决方法
1.找到以下位置目录下相应的文件db2nodes.cfg C:\Documents and Settings\All Users\Application Data\IBM\DB2\DB2COPY1\D ...
- 如何描述bug
清晰的标题 环境描述 已经采取了什么措施 结果 日志 Coredump 截图
- atom 插件安装【转载】
http://www.cnblogs.com/20145221GQ/p/5334762.html 问题: 输入apm install后,可能一直没有响应,要强行退. 不知道安装的时候可不可以打开ato ...
- PHP 之base16加密解密封装
/** * @Description: base16加密 * @Author: Yang * @param $data * @return string */ function base16_enco ...
- Xilinx FPGA的专用时钟引脚及时钟资源相关
主要参考了https://www.eefocus.com/liu1teng/blog/12-02/237897_4533d.html .Xilinx UG471.UG472以及Xilinx Forum ...
- zoj 3314 CAPTCHA(纯模拟)
题目 有些人用深搜写的,当然我这弱弱的,只理解纯模拟... 纯模拟,第一次写了那么长的代码,我自己也是够坚韧不拔的,,,,必须留念啊!!! 注意,G包含C,E包含L,R包含P,(照图说O应该不包含C, ...
- 关于javascript原型链的记录
构造函数拥有名为prototype属性,每个对象都拥有__proto__属性,而且每个对象的__proto__属性指向自身构造函数prototype. **当调用某种方法或属性时,首先会在自身调用或查 ...
- Modbus 协议解析
- 【郑轻邀请赛 F】 Tmk吃汤饭
[题目链接]:https://acm.zzuli.edu.cn/zzuliacm/problem.php?id=2132 [题意] [题解] 很容易想到用队列来模拟; 这个队列维护的是正在煮的4个人煮 ...