ITPub博客

首页 > IT职业 > IT职场 > 玩转数据结构之数组

玩转数据结构之数组

IT职场 作者:船头尺 时间:2021-09-09 09:30:06 0 删除 编辑

Where to use Data structure?

图片描述

Data structure

图片描述

Why learn data structure?

  • Get the top company's offer
  • Better coding
  • Change the world

注意事项

Pythonic的写法可能比逻辑本身更重要, 当然,其他语言也有类似的情况。

arr[]
for i in range(10)
    arr.append(i)
效率低
arr = [i for i in range(10)]

Array

public class Main {

    public static void main(String[] args) {

        int[] arr = new int[10];
        for(int i = 0 ; i 

然后我看了下class文件

int[] var8 = scores;
        int var4 = scores.length;

        for(int var5 = 0; var5 

封装自定义数组

图片描述


public class Array {
    // E代表数据类型
    private E[] data;
    private int size;

    // 构造函数,传入数组的容量capacity构造Array
    public Array(int capacity){
        data = (E[])new Object[capacity];
        size = 0;
    }

    // 无参数的构造函数,默认数组的容量capacity=10
    public Array(){
        this(10);
    }

    // 获取数组的容量
    public int getCapacity(){
        return data.length;
    }

    // 获取数组中的元素个数
    public int getSize(){
        return size;
    }

    // 返回数组是否为空
    public boolean isEmpty(){
        return size == 0;
    }

    // 在index索引的位置插入一个新元素e
    public void add(int index, E e){

        if(index  size)
            throw new IllegalArgumentException("Add failed. Require index >= 0 and index = index ; i --)
            data[i + 1] = data[i];

        data[index] = e;

        size ++;
    }

    // 向所有元素后添加一个新元素
    public void addLast(E e){
        add(size, e);
    }

    // 在所有元素前添加一个新元素
    public void addFirst(E e){
        add(0, e);
    }

    // 获取index索引位置的元素
    public E get(int index){
        if(index = size)
            throw new IllegalArgumentException("Get failed. Index is illegal.");
        return data[index];
    }

    public E getLast(){
        return get(size - 1);
    }

    public E getFirst(){
        return get(0);
    }

    // 修改index索引位置的元素为e
    public void set(int index, E e){
        if(index = size)
            throw new IllegalArgumentException("Set failed. Index is illegal.");
        data[index] = e;
    }

    // 查找数组中是否有元素e
    public boolean contains(E e){
        for(int i = 0 ; i = size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        E ret = data[index];
        for(int i = index + 1 ; i 

Test Example

图片描述

泛型

图片描述

动态数组

图片描述

大概思路就是达到临界值(增加数组容量或者减少数组容量)生成一个新数组,然后内容迁移,最后指向新数组

时间复杂度

图片描述
图片描述

均摊 amortized time complexity

图片描述

复杂度震荡

图片描述

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3016/viewspace-2803872/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-24

  • 博文量
    92
  • 访问量
    6995