• 沒有找到結果。

Basic Data structure

N/A
N/A
Protected

Academic year: 2022

Share "Basic Data structure"

Copied!
22
0
0

加載中.... (立即查看全文)

全文

(1)

Basic Data structure

講者:楊景遇

(2)

什麼是資料結構?

● In computer science, a data structure is a data organization, management, and storage format that enables efficient access and modification.

(3)

Stack

(4)

支援

● 加東西進去

● 詢問裡面最新的東西

● 把裡面最新的東西刪掉

(5)

實作-stack基礎操作

(6)

有什麼用?

處理有某種”單調性”的問題。

example:

給一個長度N的陣列a,請對每個i輸出一個最大的j滿足:

j < i

a[j] > a[i]

(7)

觀察

a = {5, 2, 6, 8, 3, 1, 7, 4}

ans = {-1, 0, -1, -1, 3, 4, 3, 6}

一個數字一旦被某個數字蓋過去,之後都不可能是答案了。

對每個i只檢查還有可能是答案的j。

還有可能是答案的a[j]會遞減,所以我們可以從大的j開始枚舉,

遇到比a[i]小的東西就刪掉,比a[i]大則找到答案,且也沒有其 他東西可刪。

比較大的j會比較早被刪,用stack維護合法的j。

(8)

實作-stack模板題

(9)

stack與遞迴的關係

遞迴是用stack實作的

● DFS

(10)

實作-用stack實作DFS

(11)

用陣列實作stack

也許有天需要在stack上二分搜也說不定。

(12)

Queue

(13)

支援

● 加東西進去

● 詢問裡面最舊的東西

● 把裡面最舊的東西刪掉

(14)

實作-queue基礎操作

(15)

有什麼用?

BFS。

處理有某種”單調性”的問題。

example:

給一個長度N的陣列a跟一個正整數k,請對每個i輸出一個最小的j 使得:

(sum of a[h]*a[h] for j <= h <= i) <= k

(16)

觀察

如果某個i的答案是j,那所有大於i的位置的答案都會大於j。

維護當前queue裡的東西的總和,如果超過就把最前面的pop掉。

(17)

實作-queue模板題

(18)

實作-用陣列實作queue

(19)

其他資料結構

(20)

補充: deque

可以從前後塞、或pop東西。

example:

給長度N的陣列a跟一個正整數k,請問所有長度為k的區間的最大 值。

請做到O(N)

(可以google “單調隊列優化”)

(21)

補充: linked-list

● 雙向跟單向

● O(1)插入、刪除資料 a -> b -> c -> d -> e

(22)

exercises

● 用stack實作河內塔過程。

● 給一個長度N的陣列a跟正整數k, A, B,請對每個i輸出一個 最小的j使得:

(令x = (sum of a[h] for j <= h <= i)) Ax^2+Bx <= k

參考文獻

相關文件

head data data NULL..

•  先定義一個struct/class Node,作為linked list的節點,裡面存資 訊和一個指向下一個Node的指標. • 

?: { machine learning, data structure, data mining, object oriented programming, artificial intelligence, compiler, architecture, chemistry, textbook, children book,. }. a

– File and index layers organize records on files, and manage the indexing data

In this section we define a general model that will encompass both register and variable automata and study its query evaluation problem over graphs. The model is essentially a

• The memory storage unit holds instructions and data for a running program.. • A bus is a group of wires that transfer data from one part to another (data,

● size() 回傳 queue

Following the supply by the school of a copy of personal data in compliance with a data access request, the requestor is entitled to ask for correction of the personal data