cs61b学习 part3

news2024/10/8 22:59:33

如果你有许多list,这里将会是大量的时间,我指的是对于单向链表查找时间复杂度O(N)相对于数组O(1)的时间复杂度会慢一些

 

所以这究竟是顺序表的编写还是链表的改进?

IntList

public class IntList {
	public int first;
	public IntList rest;

	public IntList(int f, IntList r) {
		first = f;
		rest = r;
	}

	/** Return the size of the list using... recursion! */
	public int size() {
		if (this.rest == null) {/* base case */
			return 1;
		}
		return 1 + this.rest.size();
	}

	/** Return the size of the list using no recursion! */
	public int iterativeSize() {
		/* You can not assign "this" in Java*/
		IntList p = this;
		int totalSize = 0;
		while (p != null) {
			totalSize += 1;
			p = p.rest;
		}
		return totalSize;
	}

	/** Returns the ith value in this list.*/
	public int get(int i) {
		IntList p = this;
		int nth = 0;
		if (i >= p.size()) {
			return -1;
		}
		while (nth != i) {
			p = p.rest;
			nth += 1;
		}
		return p.first;
	}

	public static void main(String[] args) {
		IntList L = new IntList(15, null);
		L = new IntList(10, L);
		L = new IntList(5, L);
		System.out.println(L.size());
		System.out.println(L.iterativeSize());
		System.out.println(L.get(2));
	}
} 

SLList 


 /** An SLList is a list of integers, which hides the terrible truth
   * of the nakedness within. */
public class SLList {	
	private static class IntNode {
		public int item;
		public IntNode next;

		public IntNode(int i, IntNode n) {
			item = i;
			next = n;
			System.out.println(size);
		}
	} 

	/* The first item (if it exists) is at sentinel.next. */
	private IntNode sentinel;
	private int size;

	private static void lectureQuestion() {
		SLList L = new SLList();
		IntNode n = IntNode(5, null);
	}

	/** Creates an empty SLList. */
	public SLList() {
		sentinel = new IntNode(63, null);
		size = 0;
	}

	public SLList(int x) {
		sentinel = new IntNode(63, null);
		sentinel.next = new IntNode(x, null);
		size = 1;
	}

 	/** Adds x to the front of the list. */
 	public void addFirst(int x) {
 		sentinel.next = new IntNode(x, sentinel.next);
 		size = size + 1;
 	}

 	/** Returns the first item in the list. */
 	public int getFirst() {
 		return sentinel.next.item;
 	}

 	/** Adds x to the end of the list. */
 	public void addLast(int x) {
 		size = size + 1; 		

 		IntNode p = sentinel;

 		/* Advance p to the end of the list. */
 		while (p.next != null) {
 			p = p.next;
 		}

 		p.next = new IntNode(x, null);
 	}
 	
 	/** Returns the size of the list. */
 	public int size() {
 		return size;
 	}

	public static void main(String[] args) {
 		/* Creates a list of one integer, namely 10 */
 		SLList L = new SLList();
 		L.addLast(20);
 		System.out.println(L.size());
 	}
}

3 DLList(LinkedListDeque链表双边队列)


/**
 * Created by JianjunChen on 08/16/2020
 * This is a Linked List Doubly ended queue Data Structure using Lists!
 * @Rule The amount of memory that your program uses at any given time must be
 * proportional to the number of items.
 * @Rule Do not maintain references to items that are no longer in the deque.
 * @Rule Implement all the methods listed above in “The Deque API” section.
 */


public class LinkedListDeque<T> {
    /**LinkedNode Nested Class*/
    private class LinkedNode {
        private LinkedNode prev; /* Doubly Linked List*/
        private T item;
        private LinkedNode next;

        public LinkedNode(LinkedNode p, T i, LinkedNode n) {
            prev = p;
            item = i;
            next = n;
        }
    }

    private LinkedNode sentinel;
    //private LinkedNode last;
    private int size;

    /** Constructor of LinkedListDeque */
    public LinkedListDeque() {
        sentinel = new LinkedNode(null, null, null);
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
        //last = sentinel;
        size = 0;
    }

    /** Adds an item of type T to the front of the deque.*/
    public void addFirst(T item) {
        LinkedNode first = new LinkedNode(sentinel, item, sentinel.next);
        /* Note that the order cannot be reversed since if we firstly write
         * sentinel.next = first; the sentinel.next.prev will equal to first.prev!!!!*/
        sentinel.next.prev = first;
        sentinel.next = first;
        size += 1;
    }

    /** Adds an item of type T to the back of the deque. */
    public void addLast(T item) {
        LinkedNode last = new LinkedNode(sentinel.prev, item, sentinel);
        /* Note that the order cannot be reversed!!! */
        sentinel.prev.next = last;
        sentinel.prev = last;
        size += 1;
    }

    /** Returns true if deque is empty, false otherwise. */
    public boolean isEmpty() {
        if (sentinel.next == sentinel) {
            return true;
        }
        return false;
    }

    /** Returns the number of items in the deque. */
    public int size() {
        return size;
    }

    /* Prints the items in the deque from first to last, separated by a space. */
    public void printDeque() {
        LinkedNode p = sentinel;
        while (p.next != sentinel) {
            System.out.print(p.next.item + " ");
            p = p.next;
        }
    }

    /** Removes and returns the item at the front of the deque.
    If no such item exists, returns null.*/
    public T removeFirst() {
        if (isEmpty()) {
            return null;
        }

        T firstItem = sentinel.next.item;
        /* Note that the order cannot be reversed!!!*/
        sentinel.next.next.prev = sentinel;
        sentinel.next = sentinel.next.next;

        size -= 1;
        return firstItem;
    }

    /** Removes and returns the item at the back of the deque.
     * If no such item exists, returns null. */
    public T removeLast() {
        if (isEmpty()) {
            return null;
        }

        T lastItem = sentinel.prev.item;
        /* Note that the order cannot be reversed!!! */
        sentinel.prev.prev.next = sentinel;
        sentinel.prev = sentinel.prev.prev;

        size -= 1;
        return lastItem;

    }

    /** Gets the item at the given index, where 0 is the front, 1 is the next item,
    * and so forth. If no such item exists, returns null. Must not alter the deque! */
    public T get(int index) {
        if (index > size - 1) {
            return null;
        }

        LinkedNode p = sentinel.next;
        int i = 0;
        while (i != index) {
            p = p.next;
            i += 1;
        }
        return p.item;
    }

    /** Helper method for getRecursive */
    private T getRecursiveHelper(LinkedNode currentNode, int index) {
        if (index == 0) {
            return currentNode.item;
        }
        return getRecursiveHelper(currentNode.next, index - 1);
    }

    /** Same as get but using recursion!! */
    public T getRecursive(int index) {
        if (index > size - 1) {
            return null;
        }

        return getRecursiveHelper(sentinel.next, index);
    }
}

4 AList(ArrayDeque数组双边队列) 


/**
 * Created by JianjunChen on 08/18/2020
 * This is a Array based Doubly Ended Queue Data Structure!!
 * @Rule The starting size of your array should be 8.
 * @Rule Implement all the methods listed above in “The Deque API” section.
 * @Rule The amount of memory that at any given time must be proportional to the number
 * of items. For arrays of length 16 or more, your usage factor should always be at least 25%.
 *
 */


// Circular ArrayDeque
public class ArrayDeque<T> {
    private int initialCapacity = 8; //initial array capacity
    private int capacity;  //current array capacity
    private int eFactor = 2; //expanding factor
    private double usageFactor;
    private int mCapacity = 16; // The minimum capacity for contraction
    private double mRatio = 0.25; //The minimum usage ratio before contraction
    private int cFactor = 2; //contraction factor
    private T[] items;
    private int size;
    private int nextFirst;
    private int nextLast;

    public ArrayDeque() {
        capacity = initialCapacity;
        items = (T[]) new Object[initialCapacity];
        size = 0;
        nextFirst = 4;
        nextLast = 5;
    }

    /** Finding the next nextFirst and nextLast index in circle ArrayDeque. */
    private int oneMinus(int index) {
        if (index == 0) { // whether the index is out of bounds!
            index = capacity - 1;
        } else {
            index -= 1;
        }
        return index;
    }

    private int onePlus(int index) {
        if (index == capacity - 1) { // whether the index is out of bounds!
            index = 0;
        } else {
            index += 1;
        }
        return index;
    }

    /** Resize the original array to a new array with given capacity. */
    private void resize(int newCapacity) {
        T[] a = (T[]) new Object[newCapacity];

        int currentFirst = onePlus(nextFirst);
        int currentLast = oneMinus(nextLast);

        if (currentFirst < currentLast) {
            int length = currentLast - currentFirst + 1;
            System.arraycopy(items, currentFirst, a, 0, length);
            nextFirst = newCapacity - 1;
            nextLast = length;
        } else {
            int firstRightCount = capacity - currentFirst;
            int firstLeftCount = capacity - firstRightCount;
            System.arraycopy(items, currentFirst, a, 0, firstRightCount);
            System.arraycopy(items, 0, a, firstRightCount, firstLeftCount);

            nextFirst = newCapacity - 1;
            nextLast = capacity;
        }

        capacity = newCapacity;
        items = a;

    }

    /** Adds an item of type T to the front of the deque.
     * @Rule Must take constant time, except during resizing operations.
     */
    public void addFirst(T item) {
        items[nextFirst] = item;
        size += 1;
        nextFirst = oneMinus(nextFirst);

        //The array is full, needed resize operation!
        if (size == capacity) {
            resize(size * eFactor);
        }
    }

    /** Adds an item of type T to the back of the deque.
     * @Rule Must take constant time, except during resizing operations.
     */
    public void addLast(T item) {
        items[nextLast] = item;
        size += 1;
        nextLast = onePlus(nextLast);

        //The array is full, needed resize operation!
        if (size == capacity) {
            resize(size * eFactor);/*此处原为+1*/
        }
    }

    /** Returns true if deque is empty, false otherwise. */
    public boolean isEmpty() {
        if (size == 0) {
            return true;
        }
        return false;
    }

    /** Returns the number of items in the deque. */
    public int size() {
        return size;
    }

    /** Prints the items in the deque from first to last, separated by a space. */
    public void printDeque() {
        if (isEmpty()) {
            return;
        }
        int index = onePlus(nextFirst);
        while (index != nextLast) {
            System.out.print(items[index] + " ");
            index = onePlus(index);
        }
    }

    private void contract() {
        usageFactor = (double) size / capacity;
        if (usageFactor <= mRatio && capacity >= mCapacity) {
            int newCapacity = capacity / cFactor;
            resize(newCapacity);
        }
    }

    /** Removes and returns the item at the back of the deque. If no such item exists, returns null.
     * @Rule must take constant time, except during resizing operations.
     */
    public T removeFirst() {
        if (isEmpty()) {
            return null;
        }

        int currentFirst = onePlus(nextFirst);
        T currentFirstItem = items[currentFirst];
        nextFirst = currentFirst;
        items[nextFirst] = null;
        size -= 1;

        contract();

        return currentFirstItem;
    }

    /** Removes and returns the item at the back of the deque. If no such item
     * exists, returns null..
     * @Rule must take constant time, except during resizing operations.
     */
    public T removeLast() {
        if (isEmpty()) {
            return null;
        }

        int currentLast = oneMinus(nextLast);
        T currentLastItem = items[currentLast];
        nextLast = currentLast;
        items[nextLast] = null;
        size -= 1;

        return currentLastItem;
    }

    /**
     * Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth.
     * If no such item exists, returns null. Must not alter the deque!
     * @Rule must take constant time.
     */
    public T get(int index) {
        if (index >= size) {
            return null;
        }

        int indexFromFirst = nextFirst + 1 + index;
        if (indexFromFirst >= capacity) {
            indexFromFirst -= capacity;
        }

        return items[indexFromFirst];
    }
}

C、203

 100+101+....+999+1000=495550,大概500000

这张图片展示SLList代表Single-Linked List(单向链表),而ALList代表Array-Backed List(数组支持链表)的区别,即O(N)和O(NlogN)存疑

为了让alist更加通用实现了如下变化 

/* Array based list.
@author Josh Hug
 */
//        0  1  2  3  4  5  6  7
//items:[ 6  9  -1 2  0  0  0  0]
//size:5
/*Invariants:
    addlast:The next item we want to add,will go into position size
    getlast:The item we want to return is in position size -1
    size:The number of items in the list should be size.
*/
public class AList<Item> {
    private Item[] items;
    private int size;

    /**
     * Creates an empty list.
     */
    public AList() {
        items = (Item[]) new Object[100];
        size = 0;
    }

    /*Resizes the underlying array to the target capacity.*/
    private void resize(int capacity) {
        Item[] a = (Item[]) new object[capacity];
        System.arraycopy(items, 0, a, 0, size);
        items = a;
    }

    /*Inserts x into the back of the list.*/
    public void addLast(Item x) {
        if (size == items.length) {
            resize(size + 1);
        }
        items[size] = x;
        size = size + 1;
    }

    /*Returns the item from the back of the List.*/
    public Item getlast() {
        return items[size - 1];
    }

    /*Gets the ith item in the list (0 is the front).*/
    public Item get(int i) {
        return items[i];
    }

    /*Returns the number of items in the list.*/
    public int size() {
        return size;
    }

    /*Deletes item from back of the list and returns deleted item.*/
    public Item removeLast() {
        Item x = getLast();
        items[size - 1] = null;
        size = size - 1;
        return x;
    }
}

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2197408.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

webGL进阶(二)物体运动

效果&#xff1a; 模拟时钟效果。 代码&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewpo…

LSTM变种模型

一、GRU 1.概念 GRU&#xff08;门控循环单元&#xff0c;Gated Recurrent Unit&#xff09;是一种循环神经网络&#xff08;RNN&#xff09;的变体&#xff0c;旨在解决标准 RNN 在处理长期依赖关系时遇到的梯度消失问题。GRU 通过引入门控机制简化了 LSTM&#xff08;长短期…

Python爬虫使用实例-jsyks

目标地址&#xff1a; https://www.jsyks.com/kmy-mnks例如&#xff1a; urlhttps://www.jsyks.com/kmy-mnks # kmy-mnks 科目一-模拟考试 urlhttps://www.jsyks.com/kms-mnks # kms-mnks 科目四-模拟考试一、获取资源 先从本题分析里面得到解析答案【通过div.Exam ul li里面…

面向对象技术——设计模式

目录 层次结构 具体设计模式分类 创建型模式&#xff08;处理创建对象&#xff09; 结构型模式&#xff08;处理类和对象的组合&#xff09; 行为型模式&#xff08;描述类或者对象的交互行为&#xff09; 创建型设计模式 ​编辑 结构型设计模式 行为型设计模式​编辑 …

时序论文17|ICML24 SAMformer:华为新奇视角讨论Transformer时序预测时的收敛优化问题

论文标题&#xff1a;SAMformer: Unlocking the Potential of Transformers in Time Series Forecasting with Sharpness-Aware Minimization and Channel-Wise Attention 论文链接&#xff1a;https://arxiv.org/abs/2402.10198 代码链接&#xff1a;https://github.com/rom…

从零开始:在 VMware ESXi 环境中安装 Rocky Linux 的秘诀

哈喽大家好&#xff0c;欢迎来到虚拟化时代君&#xff08;XNHCYL&#xff09;。 “ 大家好&#xff0c;我是虚拟化时代君&#xff0c;一位潜心于互联网的技术宅男。这里每天为你分享各种你感兴趣的技术、教程、软件、资源、福利…&#xff08;每天更新不间断&#xff0c;福利…

appium中的uiautomatorviewer显示的界面为横屏解决方法

uiautomatorviewer显示的界面为横屏解决方法 解决方法&#xff1a; 修改模拟器的分辨率&#xff0c;比如540:900就可解决了

MySQL基础教程(一):连接数据库和使用表

这个专栏用来讲解 MySQL 数据的基本语法和用法。本教程的目的是方便查询 MySQL 的用法&#xff0c;因此对于原理的讲解会偏少一些&#xff0c;但特点就是会有很多实验操作图。 本专栏使用的源材料是《MySQL必知必会》这本书的源代码。 文章目录 1. 连接 MySQL 数据库2. 创建数…

搭建个人博客--1、前端页面

采用bootstrap前端框架&#xff1a; Anchor - a free Bootstrap UI Kit综合使用bootstrap框架做一个Aotm Blog个人博客_基于bootstrap的博客-CSDN博客 做出模板base.html {% load static %} <!DOCTYPE html> <html langen> <head><meta charset"UT…

Facebook账单户和海外户该如何选择?

近期&#xff0c;有不少小伙伴来咨询广告投放账户的问题&#xff0c;很多人把账单户作为广告投放的选择&#xff0c;那么账单户和海外户哪个更适合你呢&#xff1f;本文将详细探讨这两种账户类型的差异&#xff0c;以及在不同情境下应如何选择&#xff0c;感兴趣的朋友就继续看…

遨游双卫星智能终端,赋能石油行业安全生产和信息化建设

石油&#xff0c;被誉为“工业的血液”&#xff0c;其影响力深远&#xff0c;石油勘探与开发活动往往在人迹罕至的偏远区域展开&#xff0c;如广袤的戈壁滩、浩瀚的海洋&#xff0c;这些区域普遍缺乏健全的公共电信网络基础设施。以往&#xff0c;油田野外作业团队主要依赖短波…

避雷!Google Adsense联盟营销七大投放误区

你是否在使用Google AdSense进行广告投放&#xff1f;你是否想进一步优化你的投放策略&#xff1f;那么这篇文章你不可错过啦&#xff01; Google AdSense为跨境商家提供了一个平台&#xff0c;我们可以通过展示相关广告来赚取收入。然而&#xff0c;即使是最有经验的商家也可…

API项目:模拟接口开发和调用

创建模拟接口 controller 层&#xff1a; 控制层&#xff0c;负责处理用户请求&#xff0c;并根据请求调用相应的业务逻辑&#xff0c;然后返回对应的视图或数据。 model 层&#xff1a; 数据模型层&#xff0c;负责数据的处理和业务逻辑&#xff1b;在 model 层中&#xf…

无人机在矿业领域的应用!

矿区测绘与建模 无人机可以快速、全面地获取矿区的地形地貌数据&#xff0c;生成高精度的二维或三维模型。 这些模型可用于矿区的规划、设计、监测和管理&#xff0c;提高矿山的生产效率。 库存量量化监测 无人机能够捕捉厘米级的地形数据&#xff0c;通过计算得出准确的库…

ADC -模数转换

ADC -模数转换 - 将模拟信号转换为数字信号 目录 ADC -模数转换 - 将模拟信号转换为数字信号 STM32方面使用的AD转化方式是逐次逼近法 ADC 什么叫单次&#xff0c;连续&#xff0c;扫描&#xff0c;中断&#xff1f; 应用&#xff1a;运用STM32中ADC转…

Vue入门-小黑课堂Demo

功能需求&#xff1a; ①列表渲染 ②删除功能 ③添加功能 ④底部统计和清空 页面效果&#xff1a; 代码展示&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" c…

年会工作会议会务报名签到小程序开源版开发

年会工作会议会务报名签到小程序开源版开发 会议管理微信小程序&#xff0c;对会议流程、开支、数量、标准、供应商提供一种标准化的管理方法。以达到量化成本节约&#xff0c;风险缓解和服务质量提升的目的。适用于大型论坛、峰会、学术会议、政府大会、合作伙伴大会、经销商…

大多数人不知道的:线程池CallerRunsPolicy()拒绝策略

总所周知&#xff0c;java里面线程池的四个拒绝策略 AbortPolicy 丢弃并抛出RejectedExecutionException异常 DiscardPolicy 直接丢弃 DiscardOldestPolicy 直接丢弃最前面的任务&#xff0c;尝试执行新任务 CallerRunsPolicy 由调用线程池的线程处理任务&a…

linux安装minianconda

文章目录 &#x1f315;我的配置&#x1f315;从清华镜像源里下载minianaconda&#x1f315;安装&#x1f315;自定义安装位置&#x1f315;是否关闭打开终端默认进入anaconda的设置&#xff1f;&#x1f315;配置清华镜像源 &#x1f315;我的配置 ubuntu 22.04LTS &#x1…

全都燃起来了!黄金周车市销量成绩出炉

文/王俣祺 导语&#xff1a;国庆黄金周对于其他行业可能是个放松的好时机&#xff0c;但对于国内汽车市场而言可能是下半年最关键的“战场”。这几天&#xff0c;全国各地的车展和4S店简直热闹非凡&#xff0c;新能源车尤其抢镜&#xff0c;优惠活动不断&#xff0c;引得消费者…