Uploaded by nasia5000

CS 201 Cheat Sheets

advertisement
HASHTABLE
neuaranonarraglistanteyersvais
reedit
newanaglistanegen
HMMM
locationinanaway
usedtomaptoindex
keyvalue
imatn.powa.gl
eachelementiscalledabucket
mmmm
operations
buckets
keytnuveren of
collisions
multiple
itemsi nserted
bucket
same
into
CHAINING
vanrennatypetoobiatimmom.ae
v comparisons
shanaecollisionbyasinglistroreachbacket
streenaiscstranceannosmequaisignorecaseisnall
eANtDo
Declaration
c.nustascinneacistnewcinreacistctsa
users
rerennavariableurersbutaoesnicreatobiect
cowsmuonua
getusethumounadaysized
istonmemoryaamessorobiat
anocalememonginitialirobiathycallingaconsimetrunnerustusarrayust
anewoperator
Accessing
RING
stra.cnaratexs
cnar
malateassandriremattinelarmament.me
nw
gnaiaccess
master.gs
Accessorstmutators
enginstrength
appendend strestraorsteconcates
mm
setoperations
unionintersectiondifference
object
SETADTwearin
xbatnoty
modify
parameter
thisimplicit
of
oatmannabeforemetraname
collection d istinct
elements
stanceleassementors
unordered
sancivanabiestosinnemongonly
aassuanabeauardinciasswitnstaticregword
consimatonorbiou
stancmentorinarenantorcassobieet
ocantusenthis
ouseatoaccessimutaternvalestancreas
aromouisianeuass
LISTADT
Element
keysremoval
nnsizedtonexten.me
Wh
factor
load
w
element
search
returns
HASHSET
sclassaniedrumbaselsuperclass
inheritanceinherits
properties
class
base
declaration Hasnsetershashset newitasnsetson
adduntumsraiseiformentaleadyinset
containsclaimeiferementinset
utusconsininas
size oreementsinset
mmmmm
mmmm
brasteraccessbitnoguaranteoforder
ranaesmanents
exeunagecas
time
image
mesas
error
dynamic
supportslistoperationsbutwill
alloateawayasneededas ofelementschan
mm
or
oritems buckets
DERIVED
C LASS
specified
with
key
iserraivates
2N 2
ontheirreyvalue
unmovemetindemonselement
S UBSETS
SEARCHING
AND
man
cats
ease
noepeatingements
onaduringaprogram'sexecution
havegiobaiscope
extenaskeywordarterdened
name
class
ex
access
member
class
DenudaassextenasBaseclass
of
private
members baseclass
oequaislotrerobie.tl
objects
estequalityor
contents
their
not
references
constant
timeoperation
itemadeledwrenallocationsizelistiengt
allocated
withalengthrownmec
rewaway
ngos
mm
mm
ow
to
Prependadd beginning
mm
INTERFACE
tostatetataassaarenestomesderinabyit
specirysetorabstractmethoasmatimplementing
aassmustovernaeandarine
mustlistinterracenameafterimplements
oveniaestimplementsinterrace'sabstract
methods
an
na
exitioop
immediately
www.mmm.mn
www.aatatypecsanaynamenewaatatgpecnumeiements
anaatorioortoastingianay
ginganamagninitializesanay
tataivaecenchtfiijii.itngias
noctures
BIGONOTATION
• PSVM: Public Static Void Main
◦method:
‣ public - can call outside of class
have access to ‣ static - belongs to class not object
‣ void - no return
‣ main - starting point for program to run
‣ dynamic - called on a created object and
object data and arguments
‣ static - called on a class and only have access to arguments
Object Oriented Programming (OOP)
• ArrayList <-> Array conversion
• Classes and Objects:
◦convert an int(or other primitive type) array to arrayList by adding one element at a time:
◦class specifies the data and operations for a type of object
‣ ArrayList<Integer> intArrayList = new ArrayList<>();
‣ objects are instances of a class
‣ int[] intArray = {2,0,1};
◦instance variables: defined value
‣ for (int number : intArray){
◦constructor method: specifies how to create a new object of class
intArrayList.add(number);
◦this: refers to object on which method is called
}
◦. operator accesses instance variables or methods of obj
◦
convert
an
Integer
list
to
an int[] one at a time
◦method: defined inside class
‣ int[] newIntArray = new int[intArrayList.size()];
‣ 2 reasons to call: for side effect (what it did to the object) and for return value (no
‣ for (int i = 0; i<intList.size(); i ++){
change to object)
newIntArray[i] = intList.get(i);
Sets and Maps:
}
• Array vs Collection:
◦array
‣ stores primitives
◦collection
‣ store objects only - use wrapper for primitives(Integer)
• Sets
• Maps
◦store unique elements
◦check if element in set using .contains()
◦add element using .add() - return false if already there
◦remove element with .remove()
◦no guarantee of order stored
◦ Looping over a set:
‣ enhanced for loop - for (String s : mySet){}
◦convert between lists and sets List<String> MyList = new ArrayList<>();
myList.addAll(mySet);
◦HashSet - EFFICIENT - constant time for basic operations (add remove contains size)
◦TreeSet - KEEPS VALUES SORTED - slightly less efficient than HashSet
◦address book - lookup value of a key
‣ put(k,v) - associate value c with key k
‣ get(k) - return value associated with key k
‣ containsKey(k) - return true if key k is in map
◦HashMap - very efficient (put, get, containsKey)
◦TreeMap - nearly efficient, keeps keys sorted
◦DONT USE .get(key) if not certain that its in the map - will cause program to crash
‣ check with .containsKey() first
◦Adding default values: 2 ways
‣ .putIfAbsent(key, val)
‣ check if does not contain key and then use put
◦Updating Maps:
‣ Single Values:
• .get() returns a copy of the value
• .put() to update
‣ Collection values:
• .get() returns reference to collection
•
• update collection directly
RUNTIME EFFICIENCY
◦string concatenation
‣ A: use string object and basic + operator
• 3*(i+1) characters copied per iteration
• copies 3/2(reps)^2 characters
‣ B: use StringBuilder object and append method
• copies 3xreps characters
• B MUCH MORE EFFICIENT - asymptotically
◦We often use asymptotic notation (Big O notation) to abstract away from
constants
‣ let N = reps - asymptotic runtime complexity is O(N^2)
• double N, quadruple runtime
• ArrayList operations
◦BUT....efficiency:
StringBuilder(B) uses 1.5x as much memory as necessary
◦get()
constant
time
not
dependent on list size
◦StringBuilder grows geometrically
◦contains() - loops
array
calling .equals() at each step - longer as
‣ like thorugh
ArrayList,
HashMap
list grows
◦size() - returns value of instance variable tracking size - does not depend
on size
◦add() - depends
• HASHING EFFICIENCY
◦real runtime of get(), put(), and containsKey() =
‣ time to get the hash
‣ + time to search over the hash index "bucket".. calling .equals()
on everythign in bucket
• Memory/runtime tradeoff
◦N pairs, M buckets
‣ 1: N>>M - too many pairs in too few buckets
• not a constant runtime (~N/M)
‣ 2: M>>N - too many buckets not many pairs
• runtime constant but inefficient memory
‣ 3: M slightly larger than M
• overall runtime constant, reasonable memory usage
• still more memory used than simple ArrayList
• Load Factor + HashMap Growth:
◦N pairs M buckets - Load factor maximum N/M ratio but default 0.75
◦when N/M exceeds load factor
‣ create new larger table - rehash and copy everything
‣ double size, geometric growth for amortized efficiency like
ArrayList
‣
• O(NM) vs O(N+M):
◦O(NM):
◦O(N+M)
‣ if we double N and double M: runtime increases by factor of 4
‣ N>>M and we double M: doubles runtime
‣ if we double N and double M: runtime increases by factor of 2
‣ N>>M and we double M: little difference in runtime, N dominates
.length vs .size():
• Array/strings use .length
• everything else .size()
arraylist vs hashset
memory:
• arraylist more
memory since it
stores duplicates
• arrays do not have
.contains method
•
•
•
•
•
ArrayList Runtimes:
Get() - O(1)
Contains() - O(N)
Size() - O(1)
Add() - O(1) at end
O(N) at front
Growth • add one spot each
time - O(N^2)
• Geometric - growth
O(N)
HashSet runtimes:
• O(1) for add, remove, contains, size
TreeSet is nearly the same as hashSet
efficiency but stores orders sorted
.putIfAbsent(key,value) or !
map.containsKey() followed by
map.put(key,value)
HashMap:
.equals() - looks at key compared to
what you call get on so that it can take
from bucket with multiple pairs
• any 2 objects that are equals() should
have same hashCode()
String builder:
• O(N) - copy over every character
LINKED LISTS:
Sorting:
• less efficient than ArrayList(O(1) for get)
• .sort() is stable sorting with runtime
reverence
stores
node
tori
rst
• reference/pointer to first node in a list
O(Nlog(N))
connected by a reference to the next node
runtime
list
asizes
isol
pointer
◦ .get() has runtime O(N)
final
change
just
using get() vs an iterator for linkedList:
◦ for(int i = 0; i <N; i++)
Recursive Sorting:
total+=lList.get(i);
mergesort - complexity O(Nlog(N))
• halves at each level O(log(N)) and then runs
O(N) times at each level (merge helper
method complexity)
ftp.T
Mtg
ON
y
• add/remove to front of LinkedList has runtime O(1)
so remove N from front is O(N)
REFERENCES AND MEMORY:
• variables for anything that is an object (not
primitive) really stores location of the object in
memory
• new reference type object in memory is only
created when code calls new operator
• + means a comes after b
• COMPARABLE CREATING YOUR OWN CLASS
COMPARABLE
• comparator with lambda:
◦ sort something without a getter method
◦ ex. sort an array of arrays by first elements
Null: the default value for an uninitialized
object
• denotes end of list if object == null
• if you try to call any methods on null object
you get a null pointer exception error
Nodes:
• if you call new Node() - creating a node in
memory that did not exist
• node.next = otherNode makes node point
to otherNode
• node.next give null if list runs out
• node.info and node.next give null pointer
exception if node is null
• removing first node
◦ add reference to second node of list
• any situations you can use comparable you can also use
comparator but not other way around
• use comparable when making own class and want to compare
objects in that class
◦ only compareTo - uses .compare()
• use comparator when you want to sort on something besides
natural order or when given the class
◦ can only use .comparing() or making own class
ArrayList with n elements, the runtime complexity of
myList.remove(n/2) - which removes the middle element
of myList - RUNTIME COMPLEXITY O(N) - has to shift
everything over once it removes that element
ON
front
Oct adds
to
ON TOTAL
Binary Search Code:
RUNTIMES:
• mergesort and quicksort - O(Nlog(N))
• insertionsort - O(N^2)
• linkedlist: add to beginning O(1), add to
middle/end O(N)
• binary search: O(log(N))
TESTING
***BINARY SEARCH ASSUMES LIST IS ALREADY SORTED***
Tree Traversals: 2T(n/2) + O(1) = O(n)
Trees
8,4,6,12,10,15
6,4,10,15,12,8
Binary Search Trees: left subtree values are all 4,6,8,12,10,15
less than nodes value and right subtree values
are all greater than nodes value
• O(log(N)) search, add, remove
Red Black Trees: must be BST
1. every node is red or black
2. root is black
3. red node cannot have red children
4. from a given node, all paths to null
descendants must have the same number
of black nodes (null is a black node)
Binary Heaps: every node must be greater than
or equal to its parent and must satisfy shape
property
• implemented with priority queue
• nodes represented in heap array - left to
right by level
• left child index: 2*k, right child: 2*k+1,
parent: k/2
• O(log(N)) remove/add
• peek: O(1)
• complete: O(log(N)) height
• adding values to heap:
◦ add to first open position in last level
of tree(end of array)
◦ swap with parent if heap property is
violated
‣ stop when parent is smaller or
reach root
• adding to heap implementation
Nodes in Huffman Coding Tree With M
Unique Characters: O(M)
O(Mlog(M)) runtime - M-1 iterations of log(M)
removal from priority queue
Tree Insert/Search:
Balanced: T(N/2) +O(1) = O(log(N))
Unbalanced: every node has a right child but no
left T(N-1) +O(1) = O(N)
Graphs:
Efficient Adjacency "LIst" Using Double Hashing
• HashMap<Vertex. HashSet<Vertex>> aList
undirected: edges go both ways
directed: edges go only one way
simple: one undirected or two directed edges between
each node
size: N nodes, M edges M<=N^2
Recursive DFS in Grid Graph:
• represented as 2D array... char[][]
• always explore new adjacent vertex if possible, if not,
backtrack to most recent vertex adjacent to an unvisited
vertex and continue
• keep track of visited nodes to avoid infinite recursion
◦ base cases: searching off grid (161), already
explored (162), found middle (172)
• runtime: O(1) for each recursive call. if N = width*height
◦ each node recursed on <= 4 times --> O(N) overall
Dijkstra's Algorithm:
• order priority by distance of shortest path found
so far to given node
• explore next closest unexplored node to start at each iteration
• 66: N iterations
• 67: O(log(N)) - heap
• 68: O(log(N)) in
TreeMap
• overall:
O((N+M)log(N))
Iterative DFS:
• stack LIFO
Iterative BFS:
• queue FIFO
• explore from one current node at a time
• N+2M - O(N+M)
• N+2M - O(N+M)
Download