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 ...
随机推荐
- UICollectionView框架总结
一.UIcollectionView介绍 1.1.简介 首先看苹果官方文档 UICollectionView Class Reference 的介绍: The UICollectionView cla ...
- Vue ui 大法哪家强?
Element iView Vuex Mint UI Vant cube-ui,对比六大 vue ui 组件库,选中最适合的那个. Element(pc) 介绍 & 版本 饿了么前端团队开发的 ...
- (ccf)201703-3markdown
#include<iostream> #include<memory.h> #include<stack> #include<string> #incl ...
- rpm包下载地址
https://dl.fedoraproject.org/pub/epel/6/x86_64/
- Mysql学习总结(40)——MySql之Select用法汇总
一.条件筛选 1.数字筛选:sql = "Select * from [sheet1$] Where 销售单价 > 100" 2.字符条件:sql = "Selec ...
- HDU 3208 Integer’s Power
Integer’s Power Time Limit: 1000ms Memory Limit: 32768KB This problem will be judged on HDU. Origina ...
- Nginx不转发http header
使用nginx做http代理时,在Header中使用了一个名为api_key的属性,碰到http header不转发的问题. 问题源码: rc = ngx_http_parse_header_line ...
- PatentTips - Zero voltage processor sleep state
BACKGROUND Embodiments of the invention relate to the field of electronic systems and power manageme ...
- nyoj_8_一种排序_201311251238
一种排序 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复:还知道这个长方形的宽和长,编 ...
- [转]C#操作SQL Server数据库
转自:C#操作SQL Server数据库 1.概述 ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: 第一,使用SqlConnection对象连接数据库: 第二,建立SqlComman ...