算法 & 数据结构学习心得

174 阅读1分钟

一、什么是数据结构?什么是算法?

  数据结构是计算机存储、组织数据的方式,算法就是操作数据的一组方法。

二、有啥用?

 1)写出时间复杂度 & 空间复杂度低的优秀代码。
 2)思考问题的一种思维方式。

三、如何使用?

1)时间复杂度
2)空间复杂度
3)平均时间复杂度
4)均摊时间复杂度

四、常用的有哪些?

 1) 数组- ArrayList 
 2) 链表- LinkedList  

五、如何用好常用的数据结构和算法?

单链表反转的三种方式:利用栈 & 原地反转(递归 & while循环)

那么究竟应该选择哪种方式呢?

1.利用栈的特性实现反转

额外空间复杂度由链表长度决定O(n),时间复杂度分为存取是一个线性时间O(n) alt

2.原地反转(递归)

额外空间复杂度 引入了newHead 为O(1),时间复杂度为O(n) 由链表的长度解决。

static Node reverseByRecursion(Node head){
   if(head == null || head.next == null){
       return head;
   }

   Node newHead = reverseByRecursion(head.next);

   head.next.next = head;
   head.next = null;
   return newHead;
}

alt

3.原地反转(while循环)

额外空间复杂度引入preNode & nextNode ,所以为O(1);时间复杂度为链表长度O(n)

class Node {
    int data;
    Node next;

    Node(int data){
        this.data = data;
    }
}

Node reverseByLoop(Node head) {
    if (head == null || head.next == null){
        return head;
    }

    Node preNode = null;
    Node nextNode = null;
    while (head != null){
        nextNode = head.next;

        head.next = preNode;
        preNode = head;
        head = nextNode;
    }
    return preNode;
}
 我们一般选择实现方案,都需要从空间复杂度 & 时间复杂度方面去分析,然后采用合适的算法;从上面可以看出原地反转方案应该是首选,那么两个原地反转方案的空间复杂度 & 时间复杂度都是一样的,我们又要如何去选择方案呢?