相似的事物放一起,是讓環境井然有序的關鍵,這也是電腦世界中陣列(Array)此資料結構的設計理念。 因為事物都在同處,我們可藉索引在常數時間(O(1))內找到對應元素(隨機存取)。
如果不是相似的事物,如果不放在一起,我們還有方法能好好整理它們嗎?可以,用鍵(Key)值(Value)架構即可。 我們先定好一個雜湊(Hashing)函數,讓要管理的事物都依循此函數的判斷放到對應區塊中。這樣就能在常數時間(O(1))內找到鍵所對應的值。
Notes:
- 有時反向遍歷陣列,做法會簡單很多
- 程式碼要一開始就簡潔很難,寫完再整理比較容易
- 善用陣列索引的有序性,有時會比雜湊表還好用
跨倉庫導讀#
#1
Two Sum
#14
Longest Common Prefix
#27
Remove Element
#28
Find The Index of The First Occurrence in a String
#36
Valid Sudoku
#41
First Missing Positive
#49
Group Anagrams
#58
Length of Last Word
#68
Text Justification
#75
Sort Colors
#118
Pascals Triangle
#122
Best Time to Buy And Sell Stock II
#128
Longest Consecutive Sequence
#169
Majority Element
#179
Largest Number
#187
Repeated DNA Sequences
#205
Isomorphic Strings
#217
Contains Duplicate
#238
Product of Array Except Self
#242
Valid Anagram
#271
Encode and Decode Strings
#280
Wiggle Sort
#290
Word Pattern
#303
Range Sum Query - Immutable
#304
Range Sum Query 2D Immutable
#347
Top K Frequent Elements
#380
Insert Delete Get Random O(1)
#392
Is Subsequence
#438
Find All Anagrams in a String
#448
Find All Numbers Disappeared in An Array
#496
Next Greater Element I
#523
Continuous Subarray Sum
#535
Encode and Decode TinyURL
#554
Brick Wall
#560
Subarray Sum Equals K
#605
Can Place Flowers
#665
Non Decreasing Array
#705
Design HashSet
#706
Design HashMap
#724
Find Pivot Index
#838
Push Dominoes
#912
Sort an Array
#929
Unique Email Addresses
#1189
Maximum Number of Balloons
#1299
Replace Elements With Greatest Element On Right Side
#1396
Design Underground System
#1461
Check if a String Contains all Binary Codes of Size K
#1603
Design Parking System
#1822
Sign of An Array
#1929
Concatenation of Array
#1930
Unique Length 3 Palindromic Subsequences
#1963
Minimum Number of Swaps to Make The String Balanced
#2001
Number of Pairs of Interchangeable Rectangles
#2002
Maximum Product of The Length of Two Palindromic Subsequences
#2017
Grid Game
#2215
Find the Difference of Two Arrays
#2306
Naming a Company
#2348
Number of Zero-Filled Subarrays
#2405
Optimal Partition of String
#2483
Minimum Penalty for a Shop