[数据结构]什么是数组?

待我称王封你为后i 2021-12-09 20:49 362阅读 0赞

数组:有限个相同类型的变量所组成的一个集合,数组中的每个变量可以成为一个元素,数组在内存中是顺序存储的,需要开辟连续的内存空间.
数组的特点:查找快,修改慢, 查找的时间复杂度O(1),而修改是O(n) ,其中当不关心数组的顺序时,删除操作可以用末尾的元素覆盖所要删除位置的元素,然后再删除末尾元素此时复杂度为O(1)

手敲一个简单的数组

  1. /**
  2. * @author : 董硕
  3. * @time: 2019-07-14 18:17
  4. * @desc:手写一个数组 实现add update delete find ,增加了扩容功能
  5. */
  6. public class MyArray {
  7. private int [] array;
  8. private int size;
  9. public MyArray(int size) {
  10. this.array = new int [size];
  11. this.size = 0;
  12. }
  13. public int get(int index) {
  14. return array[index];
  15. }
  16. public void update(int element , int index) {
  17. array[index] = element;
  18. }
  19. public void insert(int element , int index) {
  20. if (index < 0 || index > size) {
  21. throw new IndexOutOfBoundsException("out of array size");
  22. }
  23. if (size >= array.length) {
  24. resize();
  25. }
  26. for (int i = size - 1; i >= index; i--) {
  27. array[i+1] = array[i];
  28. }
  29. array[index] = element;
  30. size++;
  31. }
  32. public int delete(int index) {
  33. if (index < 0 || index > size) {
  34. throw new IndexOutOfBoundsException("out of array size");
  35. }
  36. int deleteElement = array[index];
  37. for (int i = index; i < size -1; i++) {
  38. array[i] = array[i+1];
  39. }
  40. size--;
  41. return deleteElement;
  42. }
  43. private void resize() {
  44. int [] newArray = new int[2 * size];
  45. System.arraycopy(this.array,0,newArray,0,size);
  46. this.array = newArray;
  47. }
  48. private void outPut() {
  49. System.out.println(JSON.toJSONString(array));
  50. }
  51. public static void main(String[] args) {
  52. MyArray myArray = new MyArray(10);
  53. myArray.insert(0,0);
  54. myArray.insert(1,1);
  55. myArray.insert(2,2);
  56. myArray.insert(3,3);
  57. myArray.insert(4,4);
  58. myArray.delete(0);
  59. myArray.insert(12,0);
  60. myArray.outPut();
  61. }
  62. }

发表评论

表情:
评论列表 (有 0 条评论,362人围观)

还没有评论,来说两句吧...

相关阅读

    相关 什么数据结构

    什么是数据结构 简单来说,程序=数据结构+算法。 传统上,我们把数据结构分为逻辑结构和物理结构。 逻辑结构:是指数据对象中数据元素之间的互相关系,也是我们今后最需要关

    相关 Java基础:什么数据结构

    一、数据结构 1、数据结构的定义   数据结构是计算机存储,组织数据的方式。数据结构是指相互之间存在一种或多种特定关系的数据元素的集合。通常情况下,精心选择的数据结

    相关 什么数据结构

    数据: 是所有能被输入到计算机中,且能被计算机处理的符号的集合。它是计算机操作的对象的总称,也是计算机处理的信息的某种特定的符号表示形式。 数据元素: 是数据(集合)中的

    相关 01 什么数据结构

    本篇作为博主的数据结构与算法的第一篇,主要什么是数据结构。后面的博客会慢慢讲到各种算法与数据结构。 数据结构和算法这门计算机必修课,非常重要的(现在感触越来越深)。以后如果你