Coursera普林斯顿算法课第二次作业

2023-11-11 17:38

本文主要是介绍Coursera普林斯顿算法课第二次作业,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Deque: 使用LinkedList和哨兵节点即可。

import java.util.Iterator;
import java.util.NoSuchElementException;import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.Stopwatch;public class Deque<Item> implements Iterable<Item> {private int num; // number of nodesprivate Node first;private Node last;public Deque(){this.num = 0;this.first = null;this.last = null;	}private class Node{private Item item;private Node next;private Node prev;}public boolean isEmpty(){return first == null;}public int size(){return num;}// add the item to the frontpublic void addFirst(Item item){if(item == null) throw new IllegalArgumentException();Node oldfirst = first;first = new Node();first.item = item;first.prev = null;if(oldfirst == null){last = first;first.next = null;	}else{first.next = oldfirst;oldfirst.prev = first;}num++;}// add the item to the endpublic void addLast(Item item){if(item == null) throw new IllegalArgumentException();Node oldlast = last;last = new Node();last.item = item;last.next = null;if(isEmpty()){first = last;last.prev = null;}else{oldlast.next = last;last.prev = oldlast;}num++;	}// remove and return the item from the frontpublic Item removeFirst(){if(isEmpty()) throw new NoSuchElementException();Item it = first.item;first = first.next;num--;if(num == 0) last = null;else first.prev = null;return it;}public Item removeLast(){if(isEmpty()) throw new NoSuchElementException();Item it = last.item;last = last.prev;num--;if(num == 0) first = null;else last.next = null;return it;}// return an iterator over items in order from front to endpublic Iterator<Item> iterator(){	return new DequeIterator();	}private class DequeIterator implements Iterator<Item>{private Node current = first;public boolean hasNext() {return current != null;}public void remove() {throw new UnsupportedOperationException();}public Item next() {if(!hasNext()) throw new NoSuchElementException();Item it = current.item;current = current.next;return it;}}// testpublic static void main(String[] args){Deque<String> dq = new Deque<String>();dq.addFirst("I");dq.addFirst("am");dq.addFirst("Hugh");dq.addLast("I");dq.addLast("Love");dq.addLast("Gals");Stopwatch sw = new Stopwatch();for(String s:dq){ StdOut.println(s);}StdOut.println("remove first: "+dq.removeFirst());StdOut.println("remove last: "+dq.removeLast());for(String s:dq){ StdOut.println(s);}StdOut.println("elapsed CPU time: "+sw.elapsedTime());}}

RandomizedQueue: 使用ResizedArray实现,关键在于在每次dequeue操作后需要把末端节点存储的item转存到被随机移除item的节点处,然后将尾端节点设为null,避免loitering。同时也能避免wrap-around的问题,即不会出现数组前几项被dequeue后值为null的情况。

import java.util.Iterator;
import java.util.NoSuchElementException;import edu.princeton.cs.algs4.StdRandom;public class RandomizedQueue<Item> implements Iterable<Item> {private Item[] que;private int num; // number of elements on queuepublic RandomizedQueue(){que = (Item[]) new Object[2];num = 0;}public boolean isEmpty(){return num == 0;}public int size(){return num;}private void resize(int capacity){assert capacity >= num;Item[] temp = (Item[]) new Object[capacity];for(int i=0; i<num; i++){temp[i] = que[i];}que = temp;}public void enqueue(Item item){if(item == null) throw new IllegalArgumentException();if(num == que.length) resize(2 * que.length);que[num++] = item;}// remove and return a random itempublic Item dequeue(){if(isEmpty()) throw new NoSuchElementException();int ch = StdRandom.uniform(num);Item it = que[ch];if(ch != num-1) que[ch] = que[num-1];que[num-1] = null; // to avoid loiteringnum--;if(num > 0 && num == que.length / 4) resize(que.length / 2);return it;}// return a random item but not remove itpublic Item sample(){if(isEmpty()) throw new NoSuchElementException();int ch = StdRandom.uniform(num);return que[ch];}// return an independent iterator over items in random orderpublic Iterator<Item> iterator() {return new RandomizedQueueIterator();}private class RandomizedQueueIterator implements Iterator<Item>{private Item[] rdq; // independent iteratorprivate int current;public RandomizedQueueIterator(){rdq = (Item[]) new Object[num];current = 0;for(int k=0; k<num; k++){rdq[k] = que[k];}StdRandom.shuffle(rdq);}public boolean hasNext() {return current < num;}public void remove() {throw new UnsupportedOperationException();}public Item next() {if(!hasNext()) throw new NoSuchElementException();Item it = rdq[current];current++;return it;}}}

Permutation:注意k是从命令行获取的,以及不要有多余的输出。在参考资料中提到了新建字符串数组和使用readStrings函数获得bonus的方法,不过实际测试时却发现如下错误:

[ERROR] Permutation.java:11: Do not declare arrays in this program. [Performance]

[ERROR] Permutation.java:11:44: Do not call 'StdIn.readAllStrings()' in this program. Use only 'StdIn.readString()'. 

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;public class Permutation {public static void main(String[] args){RandomizedQueue<String> r = new RandomizedQueue<String>();//StdOut.println(" size: " + r.size());// input from command lineint k = Integer.parseInt(args[0]);String s;//StdOut.println("Input strings: "); -> no redundant output!// use ctrl+z to end inputwhile(!StdIn.isEmpty()){//r.enqueue(s); -> the last string won't be enqueued!s = StdIn.readString();r.enqueue(s);}int count = 0;for(String ss:r){if(count < k){StdOut.println(ss);count++;}else break;}}}

references:

https://blog.csdn.net/sesiria/article/details/52586467

https://segmentfault.com/a/1190000005345079

https://blog.csdn.net/tumaolin94/article/details/43448485

这篇关于Coursera普林斯顿算法课第二次作业的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/391744

相关文章

使用雪花算法产生id导致前端精度缺失问题解决方案

《使用雪花算法产生id导致前端精度缺失问题解决方案》雪花算法由Twitter提出,设计目的是生成唯一的、递增的ID,下面:本文主要介绍使用雪花算法产生id导致前端精度缺失问题的解决方案,文中通过代... 目录一、问题根源二、解决方案1. 全局配置Jackson序列化规则2. 实体类必须使用Long封装类3.

Springboot实现推荐系统的协同过滤算法

《Springboot实现推荐系统的协同过滤算法》协同过滤算法是一种在推荐系统中广泛使用的算法,用于预测用户对物品(如商品、电影、音乐等)的偏好,从而实现个性化推荐,下面给大家介绍Springboot... 目录前言基本原理 算法分类 计算方法应用场景 代码实现 前言协同过滤算法(Collaborativ

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

Java时间轮调度算法的代码实现

《Java时间轮调度算法的代码实现》时间轮是一种高效的定时调度算法,主要用于管理延时任务或周期性任务,它通过一个环形数组(时间轮)和指针来实现,将大量定时任务分摊到固定的时间槽中,极大地降低了时间复杂... 目录1、简述2、时间轮的原理3. 时间轮的实现步骤3.1 定义时间槽3.2 定义时间轮3.3 使用时

如何通过Golang的container/list实现LRU缓存算法

《如何通过Golang的container/list实现LRU缓存算法》文章介绍了Go语言中container/list包实现的双向链表,并探讨了如何使用链表实现LRU缓存,LRU缓存通过维护一个双向... 目录力扣:146. LRU 缓存主要结构 List 和 Element常用方法1. 初始化链表2.

golang字符串匹配算法解读

《golang字符串匹配算法解读》文章介绍了字符串匹配算法的原理,特别是Knuth-Morris-Pratt(KMP)算法,该算法通过构建模式串的前缀表来减少匹配时的不必要的字符比较,从而提高效率,在... 目录简介KMP实现代码总结简介字符串匹配算法主要用于在一个较长的文本串中查找一个较短的字符串(称为

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

Python中的随机森林算法与实战

《Python中的随机森林算法与实战》本文详细介绍了随机森林算法,包括其原理、实现步骤、分类和回归案例,并讨论了其优点和缺点,通过面向对象编程实现了一个简单的随机森林模型,并应用于鸢尾花分类和波士顿房... 目录1、随机森林算法概述2、随机森林的原理3、实现步骤4、分类案例:使用随机森林预测鸢尾花品种4.1