Zhuo Han


  • 关于

  • 首页

  • 分类

  • 归档

  • 标签

  • 搜索
close

LeetCode | Anagrams

发表于 2018-03-11   |   分类于 Leetcode   |     |   阅读次数

§Anagrams

§Problem
  • 242. Valid Anagram

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    bool isAnagram(string s, string t) {
    int l1=s.length();
    if (l1!=t.length())
    return false;
    vector<int> cnt(256,0);
    for (char ch:s)
    cnt[ch]++;
    for (char ch:t){
    cnt[ch]--;
    if (cnt[ch]<0)
    return false;
    }
    return true;
    }
  • 49. Group Anagrams

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// use sort & hashmap
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,multiset<string>> ansmap;
for (auto s:strs){
string tmp = s;
sort(tmp.begin(),tmp.end());
ansmap[tmp].insert(s);
}
vector<vector<string>> ans;
for (auto str:ansmap){
vector<string> anstmp(str.second.begin(),str.second.end());
ans.push_back(anstmp);
}
return ans;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// use primer to present number
public List<List<String>> groupAnagrams(String[] strs) {
int[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103};
List<List<String>> res = new ArrayList<>();
HashMap<Integer, Integer> map= new HashMap<>();
for (String s : strs){
int key = 1;
for (char c : s.toCharArray())
key *= prime[c-'a'];
//use index as value
List<String> tmp;
if (map.containsKey(key))
tmp = res.get(map.get(key));
else{
tmp = new ArrayList<>();
map.put(key, res.size());
res.add(tmp);
}
tmp.add(s);
}
return res;
}
  • 438. Find All Anagrams in a String

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // Sliding window
    vector<int> findAnagrams(string s, string p) {
    vector<int> ans;
    vector<int> ch1(26,0), ch2(26,0);
    int l1 = s.length(), l2 = p.length();
    if (l1<l2)
    return ans;
    for (int i=0; i<l2;i++){
    ch1[s[i]-'a']++;
    ch2[p[i]-'a']++;
    }
    if (ch1==ch2)
    ans.push_back(0);
    for (int i=l2;i<l1;i++){
    ch1[s[i-l2]-'a']--;
    ch1[s[i]-'a']++;
    if (ch1==ch2)
    ans.push_back(i-l2+1);
    }
    return ans;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public List<Integer> findAnagrams(String s, String p) {
    List<Integer> res = new ArrayList<>();
    if (s == null || s.length() == 0 || p == null || p.length() == 0)
    return res;
    int[] les = new int[256];
    for (char c : p.toCharArray())
    ++ les[c];
    int l = 0, r = 0, cnt = p.length();
    int len1 = p.length(), len2 = s.length();
    while (r < len2){
    // right letter s[r] exist in p that has been matched
    if (les[s.charAt(r++)]-- >= 1)
    -- cnt;
    if (cnt == 0)
    res.add(l);
    // left letter s[l] exist in p that shoule be matched letter
    if (r - l == len1 && les[s.charAt(l++)]++ >= 0) cnt++;
    }
    return res;
    }
  • 567. Permutation in String

    the first string’s permutations is the substring of the second string -> find anagram

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // Silimar to 567
    bool checkInclusion(string p, string s) {
    vector<int> ch1(26,0), ch2(26,0);
    int l1 = s.length(), l2 = p.length();
    if (l1<l2)
    return false;
    for (int i=0; i<l2;i++){
    ch1[s[i]-'a']++;
    ch2[p[i]-'a']++;
    }
    if (ch1==ch2)
    return true;
    for (int i=l2;i<l1;i++){
    ch1[s[i-l2]-'a']--;
    ch1[s[i]-'a']++;
    if (ch1==ch2)
    return true;
    }
    return false;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public boolean checkInclusion(String s1, String s2) {
    int [] les = new int[256];
    for (char c : s1.toCharArray())
    ++ les[c];
    int l = 0, r = 0, cnt = s1.length();
    int len1 = s1.length(), len2 = s2.length();
    while (r < len2){
    // right letter s[r] exist in p that has been matched
    if (les[s2.charAt(r++)]-- >= 1)
    -- cnt;
    if (cnt == 0)
    return true;
    // left letter s[l] exist in p that shoule be matched letter
    if (r - l == len1 && les[s2.charAt(l++)]++ >= 0) cnt++;
    }
    return false;
    }
§Conclusion

Normally it is related to HashMap, sort, two pointer

System Design I

发表于 2018-03-06   |   分类于 System Design   |     |   阅读次数

§System Design I

  • reference

eg. Design a url shortening service, like bit.ly

§Process
  • Step 1: [Scope the problem]

    • Use Cases

      1. Shortening: take a url => return a shorter url
      2. Redirection: take a short url => redirect to the original url
      3. Custom url: allow users to pick their available shortened URL
      4. High availability of the system

      Others:

      1. Analytics: to look at usage statistics
      2. Automatic link expiration: automatically expire link or stay alive forever
      3. Manual link removal: the user wants to remove the link
      4. UI vs API: design a web service or a website, or a URL shortening API
    • Constraints

      • the amount of traffic & data: how many the requests a mouth should handle and how many new URLs per month should the site handle => per second
      • approcimation eg. active users: Facebook, 1.3billion; Twitter, 650 million, new tweets made per day, 500 million
      1. => 1.5BN new tweets => All shortened URL per month 1.5BN => Site below the top 3: shorten 300M per monty => We: 100M new urls per month

      2. assume average lifetime: 1-2 weeks ~ 10 days

        & assume 1 click per day,

        & 20% got much more traffic than the rest 80% => 100 mln * 10 days * 1 click per day = 1 BN requests per month => 400+ requests per second

      3. 10% from shortening, 90% from redirection => 40 shortens, 360 redirections

      4. Total urls: 5 years X 12 months X 100M = 6 BN url

      5. 500 bytes per URL => total storage of urls over 5 yrs: 6BN X 500 bytes = 3TB

      6. log(62,6BN) => 6 bytes per hash => hases: 6BN X 6 bytes = 36GB

      7. New data written per second: 40 X (500+6) = 12K

      8. Data read per second: 360 X (500+6) = 180K

      => pic

  • Step 2: [Sketch up an] Abstract design

    sketch the important components and the connections between them

    1. Aplication Design
      1. Shortening service: generate on your hash; check if it’s in the datastore, not -> store a new mapping, or -> generate new hash …
      2. Redirection service:
      3. Custom URL: take a hash from user, check if it’s a shorten URL word, check if it’s in the datastore, not -> store, or -> return a message
    2. Data storage layer (keep track of the hash => url mappings)
      1. Acts like a hash table: stores new mappings and retrieve a value given a key

    hashed_url = convert_to_base62(md5(original_url + random_salt))[:6]

  • Step 3: [Think about the] bottlenecks

    eg. Perhaps your system needs a load balancer and many machines behind it to handle the user requests. Or maybe the data is so huge that you need to distribute your database on multiple machines. What are some of the downsides that occur from doing that? Is the database too slow and does it need some in-memory caching?

    1. traffic: not very challenging since it’s lightweight; think how we quickly look up URL
    2. lots of data
  • Step 4: [Address these bottlenecks by using the fundamentals principles of scalable system design] Scaling your abstract design

571 Web Technologies Review

发表于 2018-02-20   |   分类于 Course   |     |   阅读次数

§Midterm Review

  • 571 Midterm 1
  • 571 Midterm 2
  • 571 Midterm 3
  • 571 Midterm

X3_Binary Search

发表于 2018-02-10   |   分类于 Program , Leetcode   |     |   阅读次数

§Binary Tree Level Order Traversal

test case:cover different + corner case

  1. only left/right child
  2. full tree
  3. left child, right child, left child, right child…

Follow Up: output the level to level reversely from bottom to up

  1. reverse funtion
  2. add from front

§Intersection of Two Arrays

  1. If non sort-> Hashmap. Ues extra space. O(m+n)
  2. If sort-> Two pointers. O(m+n)
  3. If no extra space / If n>>m, scan the smaller array and find it in larger one via binary search in -> If already sort -> O(m*logn)

Intersection of k arrays? merge 的变种

  1. ​

§Dot Production (FB)

Conduct Dot Product of two large sparse Vectors

  1. find non-zero indexes
  2. intersection
  3. dot product

§Find K-th Smallest Pair Distance

  1. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    int lo = 0;
    int hi = nums[num.length - 1] - nums[0];
    while (lo < hi){
    int mid = lo + ((hi - lo) >>> 1);
    //...
    }

    // count function = number of pairs with distance <= guess
    if (nums[right] - nums[left] > guess)
    continue;
    count += right - left;

    Runtime: N^2*logW

  2. Optimization

    since there may be duplicate ->

    1
    2
    right = upperBound(nums, left+1, n-1, target);
    count += right - left -1
  3. Optimization II

    Use Map<Integer, Integer> to memorize

    Binary Search -> N logN * logW

§Others

§410. Split Array Largest Sum
§Copy Books, The Painter’s Partition Problem Part II
§expire map

https://www.quora.com/How-can-I-implement-expiry-key-hashmap-in-Java

cannot remove element while using for loop, but can use interator

https://stackoverflow.com/questions/6092642/how-to-remove-a-key-from-hashmap-while-iterating-over-it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class ExpiringKey implement Comparable<ExpiringKey> {
V val;
long expirationTime; // ttl
K k;
}

class ExpringMap {
Map<K, ExpiringKey> m = new HashMap<>();
PriorityQueue q

V get(Key k) {

ExpiringKey v = this.m.get(k);
if (v == null) {
return null;
}

if (v.expirationTime < System.currentTimeMillis()) {
m.remove(k);
return null;
}

return v.val;
}

void put(Key k, V val, long expirationTime) {
ExpiringKey expiringKey = new ExpiringKey(val, expirationTime);
this.m.put(k, expiringKey);
this.q.add(expiringKey); // log(k)
}

void cleanup() {
// q.poll() log(k)
List<K> keys = new ArrayList<>();
for (ExpiringKey entry : this.m.entrySet()) {
if (entry.getValue().expirationTime < System.currentTimeMillis()) {
keys.add(entry.getKey());
}
}

for (K key : keys) // delete
}

// PriorityQueue<>() minHeap
}

optimization: use PriorityQueue

§Trick

  1. search

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // search in java, return index
    if (index>=0){
    set.add(num);
    l = index;
    }
    else{
    index = -(index+1); //next one who is larger than it
    if (index >= r)
    break;
    l = index;
    }
  2. Difference between >>> and >>

    >>> is unsigned

How to write a basic Web Crawler

发表于 2018-02-09   |   分类于 Program   |     |   阅读次数

§How to write a basic Web Crawler

§Installation

  1. IntelliJ IDEA or Eclipse

  2. Crawler4j: Download latest crawler4j-x.x-jar-with-dependencies.jar

  3. Creat new a new project & Add External JARs

    Project Structure (CTRL +SHIFT +ALT + S on Windows/Linux, ⌘ + ; on Mac OS X) -> Libraries , click +

  4. Write classes as Quickstart

    Controller with main function

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    public class Controller {
    public static void main(String[] args) throws Exception {
    String crawlStorageFolder = "/data/crawl";
    int numberOfCrawlers = 7;
    CrawlConfig config = new CrawlConfig();
    config.setCrawlStorageFolder(crawlStorageFolder);
    /*
    * Instantiate the controller for this crawl.
    */

    PageFetcher pageFetcher = new PageFetcher(config);
    RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
    RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
    CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
    /*
    * For each crawl, you need to add some seed urls. These are the first
    * URLs that are fetched and then the crawler starts following links
    * which are found in these pages
    */

    controller.addSeed("http://www.viterbi.usc.edu/");
    /*
    * Start the crawl. This is a blocking operation, meaning that your code
    * will reach the line after this only when crawling is finished.
    */

    controller.start(MyCrawler.class, numberOfCrawlers);
    }
    }

    MyCrawler extends WebCrawler

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    public class MyCrawler extends WebCrawler {
    private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|gif|jpg"
    + "|png|mp3|mp3|zip|gz))$");
    /**
    * This method receives two parameters. The first parameter is the page
    * in which we have discovered this new url and the second parameter is
    * the new url. You should implement this function to specify whether
    * the given url should be crawled or not (based on your crawling logic).
    * In this example, we are instructing the crawler to ignore urls that
    * have css, js, git, ... extensions and to only accept urls that start
    * with "http://www.viterbi.usc.edu/". In this case, we didn't need the
    * referringPage parameter to make the decision.
    */

    @Override
    public boolean shouldVisit(Page referringPage, WebURL url) {
    String href = url.getURL().toLowerCase();
    return !FILTERS.matcher(href).matches()
    && href.startsWith("http://www.viterbi.usc.edu/");
    }

    /**
    * This function is called when a page is fetched and ready
    * to be processed by your program.
    */

    @Override
    public void visit(Page page) {
    String url = page.getWebURL().getURL();
    System.out.println("URL: " + url);
    if (page.getParseData() instanceof HtmlParseData) {
    HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
    String text = htmlParseData.getText();
    String html = htmlParseData.getHtml();
    Set<WebURL> links = htmlParseData.getOutgoingUrls();

    System.out.println("Text length: " + text.length());
    System.out.println("Html length: " + html.length());
    System.out.println("Number of outgoing links: " + links.size());
    }
    }
    }

    Do not forget import!

    1
    2
    3
    4
    5
    6

    import edu.uci.ics.crawler4j.crawler.CrawlConfig;
    import edu.uci.ics.crawler4j.crawler.CrawlController;
    import edu.uci.ics.crawler4j.fetcher.PageFetcher;
    import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
    import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
    1
    2
    3
    4
    5
    6
    7
    import java.util.Set;
    import java.util.regex.Pattern;

    import edu.uci.ics.crawler4j.crawler.Page;
    import edu.uci.ics.crawler4j.crawler.WebCrawler;
    import edu.uci.ics.crawler4j.parser.HtmlParseData;
    import edu.uci.ics.crawler4j.url.WebURL;

    And change your main class to com.company.Controller

  5. Some Issue

    1. SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
      SLF4J: Defaulting to no-operation (NOP) logger implementation
      SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

      Go to https://www.slf4j.org/download.html and download the newest slf4j package in http://repo2.maven.org/maven2/org/slf4j/slf4j-simple/1.7.25/.

      Add slf4j-simple-1.7.25jar to your project

    2. Exception in thread “main” java.lang.Exception: couldn’t create the storage folder: /data/crawl does it already exist ?

      Use absolute folder path, such as /Users/XXX/Desktop/XXX/HW2_WebCrawler/data/crawl

    3. If you didn’t get any result

      visit the website on your browser first

Java | Programming Fundations: Object-Oriented Design

发表于 2018-02-05   |   分类于 Program   |     |   阅读次数

§Programming Fundations: Object-Oriented Design

§Q & Term

  1. Objects are always physical or visible items. [False]
  2. Responsibilities should be stored in one master object. [False]
  3. Single Responsibility Principle and Open/Closed Principle are two of the principles of object-oriented design that are grouped under the acronym SOLID.
  4. Instantiation
  5. Data hiding/encapsulation
  6. FURPS: function, usability, reliability, performance, supportability
  7. Controlling visibility: Keeping an attribute private but creating a public operation to return the value of the attribute
  8. An interface contains [method signature] that have no functionality.
  9. Design patterns are split into the creational, structural, and behavioral groups.

§Core Concepts

  • class: name, attribution, behavior
  • Abstraction
  • Encapsulation: rescrict access -> information hiding or data hiding
  • Inheritance
  • Polymorphism: do the correct behavior for each one.

§Object-Oriented Analysis and Design

  • Process

    1. Gather your requirements: Must-do

      Functional Requirements: Feature/Capabilities

      Non-Funciontal Requirements: Help, Legalm Performance, Support, Security

      -> FURPS(Function, Usability, Reliability, Performance, Supportability)

      +Design requirements, Implementation r, Interface r, Physical r

    2. describe the application

    3. identify the most important objects

    4. describe the interaction between those objects

    5. create a class diagram

  • UML(Unified modeling Language)

§Utilizing Use Cases

  • Title(What is the goal) + Actor(Who esires it) + Scenario(How is it accomplished) + Extensions/Precondition/…

  • Use case diagram

  • User Story: As a (type of user), I want (goal), so that (reason)

  • User Stories Use Cases
    short - one index card long - a document
    one goal, no details multiple goals and details
    informal casual to (very formal)
    “placeholder for conversation” “record of conversation”

§Domain Modeling(Modeling the APP)

  1. Identifying objects: Noun List in User Case Scenario -> select as Conceptual Object Model
  2. Identifing class relationships: link & symbol
  3. Identifing class responsibilities: Verb List(what has happend/whose job) -> rename & split
  4. Using CRC(Class, ) cards
    • Class name
    • Responsibility of the class
    • Collaboratior: the other classes it interacts with

§Creating Classes

  • Class Diagram: Visibility: -private +public

    Class name eg. Product Spaceship
    Attributes - name: String = “New Product”
    - isActive: Boolean
    - launchDate: Date
    - itemNumber: Integer
    + name: String
    - shieldStringth: Integer
    …
    Operations + getName(): String
    + setActive(Bollean)
    + getProductDetails(): String
    + displayProduct()
    - formatProductDetails(): String
    + fire(): String
    + reduceShields(Integer)
    …
  • Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Spaceship{

// instance variables
public String name;
private int ShieldStringth;

//method
public String fire(){
return "Boom!";
}

public void reduceShields(int amount){
ShieldStringth -= amount;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@interface Spaceship: NSObject{
@public
NSString *name;
@private
int shieldStringth;
}
//method declarations
- (NSString *) fire;
- (void) reduceShields:(int) amount;
@end

@implementation Spaceship
- (NSString *) fire{
return @"Boom!";
}
- (void) reduceShields:(int) amount{
shieldStringth -= amout;
}
@end
  • Class lifetime

    • Instantiation

      1
      2
      3
      4
      5
      6
      Java	Customer fred = new Costomer();
      C# Customer fred = new Costomer();
      VB.NET Dim fred As New Customer
      Ruby fred = Customer.new
      C++ Customer *fred = new Costomer();
      Obective-C Customer *fred = [[Customer alloc] init];
    • Constructoe example

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      public class Spaceshio{
      ...
      // constructor method
      public Spaceship(){
      name = "Unnamed ship";
      shieldStringth = 100;
      }
      //overloaded constructor
      public Spaceship(String n){
      name = n;
      shieldStrength = 200;
      }
      ...
      }
    • Destructors/Finalizers

      1. called when an object is being deleted/deallocated/released
      2. Use for releasing resources

      A destructor is called when disposing of an object that is no longer necessary.

  • Using static/shared members

    • Static variables

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      public class SacingsAccount{
      // instance variables
      public String accountMnumber;
      private Money balance;
      //static variables
      /*
      //public (accessible) static variable
      public static float interestRate;
      // changed to private
      */

      private static float interestRate
      //public static methods
      /*static methods can only access static variable, static data.*/
      public static setInterestRate(float r){
      interestRate = r;
      }
      public static getInterestRate(){
      return interestRate;
      }
      ...
      }
      //access normal instance-level variables
      the name of the object.accountNumber
      //access a public static/shared variable
      the name of the class.interetRate

§Inheritance and Compostion

  • Using inheritance: “IS A”

    1
    2
    3
    4
    5
    6
    7
    Java	public class Album extends Product{...}
    C# public class Album : Product{...}
    VB.NET Public Class Album
    Inherits Product ...
    Ruby class Album < Product ...
    C++ class Album : public Product{...}
    Objective-C @interface Album : Product {...}
    • Overriding

      1
      2
      3
      4
      5
      6
      Jave	super.doSomething();
      C# base.doSomething();
      VB.NET Mybase.doSomething();
      Ruby super do_something
      Objective-C [super someMethod];
      C++ NamedBaseClass::doSomething();
  • Using abstract Class

    1
    2
    Java	abstract class BankAccount{...}
    VB.NET Public MustInherit Class BankAccount ...
  • Using Interfaces

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // not allowed to put functionality inside an interface
    interface Printable{
    //method sigature
    void print();
    void printToPDF(String filename);
    }
    // if implements the interface -> have to provide those 2 methods and implementation for them
    class MyClass implements Printable{
    //method bodies
    public void print(){
    //provide implementation
    }
    public void printToPDF(String filename){
    //provide implementation
    }
    }
    • Benefits: Could have many different classes choose to implement the same interface.

      eg. In Java I’d use instance of other languages do it different ways, but the concept is the same, we can just ask, does the object that I have support that particular interface, if it does, I know I can use it.

      1
      2
      3
      4
      5
      6
      while (genericObject in listOfObjects){
      if (genericObject instanceOf Printable){
      // if it implements the interface, we can use it
      genericObject.print();
      }
      }
      <>
      Printable
      print()
      printToPDF()
  • Using aggregation and composition

    • Aggregation: “HAS A” relationship of Inheritation

    • Composition: a more specific form of Aggregation, implies ownership

    • eg.

      1. Classroom[1] ——aggregation —— Student[*]

        If deleted the Classroom Object, perhaps the class got canceled -> Student objects won’t destroyed, they may be used in different classrooms or just be able to live on their own

      2. Document[1] —— composition(implies ownership) —— Page[1…*]

        But if I were to delete the Document object all the associated Page objectsshould be deleted too

§Advanced Concepts

  • Structural/Static diagrams: Class D

    -> But they are not so great at representing the lifetime of an object or actually how objects interact with one other

    -> Behavior/Dynamic diagrams: Sequence D(eg. Pleanse see 04:20’s pic)

  • UML Diagrams:

    Class Diagram, Use Case D, Object D, Sequence D, State Machine D, Activity D, Deploment D, Package D, Component D, Profile D, Communication D, Timing D, Composite Structure D, Interaction Overview D

  • UML Tools: Please see 01:32’s pic or Wikipedia page

§Object-Oriented Design Patterns

  • “Gang of Four” / “GoF” book:

    Creational Patterns, Structural P, Behavioral P

  • eg. the Singleton Pattern

    • ensure a class only has one instance

    • one way of accessing it

    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      public class MySingleton{
      // placeholder for current singleton object
      private static MySingleton _me = null;
      // private constructor - now no other object can instantiate
      private MySingleton(){}
      // this is how you ack for the singleton
      public static MySingleton getInstance(){
      // do I exist?
      if (_me == null){
      // if not, instantiate and store
      _me = new MySignleton);
      }
      return _me;
      }
      // additional functionality
      public someMethod(){//...}
      }

      // ask for the singleton
      MySingleton single = MySingleton.getInstance();
      //use it
      single.someMethod();

      //or even just call it directly
      MySingleton.getInstance.someMethod();
  • eg. the Memento Pattern

    • Handles “undo” in an object

    • Does not violate encapsulation

    • Originator: original state, Caretaker, Moemento

      C requestes O saveState => O creates a M: O: os, M, and it bundles the information up in the M and returns it to the C => C:M, O:os

      call to the O to change state => O:changed state

      calls can from C or others => O: changed again

      revert to a particular state: C:M hands back M to O => O:changed again, M, C and ask it to restore to itself => O: os

§Object-Oriented Design Priciples

  • General Softwre Development Pricibles

    1. DRY: Don’t Repeat Yourself

    2. YAGNI: You Ain’t Gonna Need it

    3. Example Code Smells

      Long methods, Very short(or long) identifiers, Pointless comments

      God object: one master object that tries to do everything in the program, or at least one object that seems to be doing very different responsibilities that have nothing to do with each other -> need to be revisited and broken apart

      Feature envy: If a class seems to do very little except use all the methods of one other class -> need to rethink the roles of one or the other

  • SOLID Priciples

    • S: Single Responsibility Principle: object should have one reason to exist, one reason to change - one primary responsibility

    • O: Open/Closed Principle: open for extension, but closed to modification

      eg. Inheritance: if get a new business requirement -> support it by adding a new class, privide some new code if it need a new business behavior, don’t change the original superclass

    • L: Liskov Substitution Principle: derived classes must be substitutable for their base classes

      if we’ve created a whole bunch of derived classes or child classes, no one can be treated specially

    • I: Interface Segregation Principle: Multiple spefic interfaces are better than one general purpose interface

      those lists of methods should be as small as possible.

      If they start to get bigger, they should be split up into smaller interfaces.Because classes can choose to implement multiple smaller interfaces, no classshould be forced to support huge lists of methods that it doesn’t need.

    • D: Dependency Inversion Principle: depend on abstractions, not on concretions

      eg. Store — AudioFileReader & AudioFileWriter

      Add a layer of abstraction -> make it more flexibility

      Store — Reader — MovieFileReader, AudioFileReader, …

      ​ — Writer — MovieFileWriter, AudioFileWriter, …

  • GRASP(General Responsibility Assignment Software Patterns) Principles

    • Creator, Controller, Pure Fabrication, Information Expert, High Cohesion, Indirection, Low Coupling, Polymorphism, Protected Variations

    • Expert/Information Expert: Assign the reponsibility to the class that has the information needed to fulgfill it

    • Creator: Who is responsible for creating an object?

    • Low Coupling/High Cohesion

      • Coupling: the level of dependencies between objects

        -> do reduce the amount of requirement connections between objects

- Cohesion: the level that a class contains focused, related behaviors

  a measure of how focused the internal behavior of a class is. Are all its behaviors related to that single responsibility?

  eg. God object has low cohesion 
  • Controller: Don’t connect UI elements directly to business objects(problem: high coupling, low cohesion)

    eg. Business Object <-> Controller Object: eg. Model View Controller <-> User Interface Object

  • Pure Fabrication: When the behavior does not belong anywhere else, create a new class

    if force that behavior into an existing class where it doesn’t belong -> decreasing Cohesion -> so we fabricate a new class

  • Indirection: to reduce coupling, introduce an intermediate object

    If you have multiple objects that need to talk to each other -> HIGH COUPLING -> so put an Ondirection Object to simplify the amount of connections -> decrease coupling between objects

  • Polymorphism: automatically correct behavior based on type

    As opposed to: conditional logic that checks for particular type -> we want to reduce checks

  • Protected Variations: protect the system from changes and viriations

    How to design a system so that changes and variations have the minimum impact on what already exists

    • Identify the most likely points of change
    • Use multiple techniques: encapsulation, LSP, OCP…

§Conclusion

  • Objective-Oriented Languages

    Language Inheritance Typing Call to super Private Methods Abstract Classes Interfaces
    Java Single static super Yes Yes Yes
    C# Single static base Yes Yes Yes
    VB.NET Single static Mybase Yes Yes Yes
    Objective-C Single static/dynamic sper No No Protocols
    C++ Multiple static name of class:: Yes Yes Abstract Class
    Ruby Mix-ins dynamic super Yes n/a n/a
    JavaScript Prototype dynamic n/a Yes n/a n/a
  • Additional resources

    Software Requirements by Karl Wiegers

    Alistair Cockburn’s Writing Effective Use Cases

    Mike Cohn’s User Stories Applied/User Stories Applied for Agile Software Development

    UML Distilled & Refactoring by Martin Fowler

    Head First Design Patterns

X2_Wiggle Sort

发表于 2018-02-04   |   分类于 Program , Leetcode   |     |   阅读次数

Subsequence: order, maynot continuous

QuickSort: Average O(NlgN), worst O(N2)

MergeSort: O(NlgN)

§Q

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,

Given [3,2,1,5,6,4] and k = 2, return 5. [3,3,3,3] and k = 1, return 3.

§A

k starts with 1, Assume k is valid

  • sol1sort O(NlgN)

  • sol2 Max-Heap, O(Nlgk)

  • sol3 quick select

    randomly choose/middle as privot

    (…discard…pivot…index….)

    time complexity: n/2 + n/4 + n/8 + … = n

    duplicate -> just move it, don’t influence

    worst case: all the number is same

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
   /**
O(N) guaranteed running time + O(1) space
randomize/shuffle the input -> O(N)

This is QuickSelect from QuickSort.
*/

public int findKthLargest(int[] nums, int k) {
int start = 0, end = nums.length - 1, index = nums.length - k;
while (start < end) {
int pivot = partition(nums, start, end);
if (pivot < index) {
start = pivot + 1;
} else if (pivot > index) {
end = pivot - 1;
} else {
return nums[pivot];
}
}

// sample input: [1]
return nums[start];
}

private int partition(int[] nums, int start, int end) {
int pivot = start;
while (start <= end) {
while (start <= end && nums[start] <= nums[pivot]) {
start++;
}
while (start <= end && nums[end] > nums[pivot]) {
end--;
}
if (start > end) {
break;
}
swap(nums, start, end);
}
swap(nums, end, pivot);
return end;
}

private void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}

§Sort Color

  • 0…0[l]1…1[r]2…2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void sortColors(int[] nums) {
// If nums is very big, it is likely to often hit page default by loading
// three sections of nums (l,m,r) and cause thrashing
int l = 0;
int r = nums.length - 1;
for (int m = 0; m <= r;) {
if (nums[m] == 0) {
swap(nums, l++, m++); //unless l == m, left = 0; left must be 1, no need to consider again
} else if (nums[m] == 2) {
swap(nums, r--, m);//since right may be 0/1/2, should consider again
} else {
m++;
}
}
}
  • What if 4 section
    • 0, 1, [2,3]; then partition 2 & 3
    • more pointers?

§Wiggle Sort I

Greedy

§Wiggle Sort II

Find Median: (nums.length+1) >>> 1, O(N)

Partition: sort color + Vitural Index, O(N)

1
2
3
4
5
6
7
  n = 6 => (n | 1) = 7
n = 7 => (n | 1) = 7
The index mapping, (1 + 2 * index) % (n | 1)
/*
vitual position: 135024, let num[135]>num[024],
then actual position 012345 will be wiggle sort.
*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public void wiggleSort2(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}

int median = findKthLargest(nums, (nums.length + 1) >>> 1);
int n = nums.length;

int left = 0, i = 0, right = n - 1;
// The index mapping, (1 + 2*index) % (n | 1) combined with 'Color sort'
while (i <= right) {
int index = newIndex(i, n);
if (nums[index] > median) {
swap(nums, newIndex(left++, n), index);
i++;
} else if (nums[index] < median) {
swap(nums, newIndex(right--, n), index);
} else {
i++;
}
}
}

// n = 6 => 012345->[1 3 5 0 2 4], 6 | 1 => 7
// n = 7 => 0123456->[1 3 5 0 2 4 6], 7 | 1 => 7

private int newIndex(int index, int n) {
return (1 + 2 * index) % (n | 1);
}

§expiry key hashmap in Java

How can I implement expiry key hashmap in Java?

1
2
3
4
5
6
7
8
class ValueWithExpiration {
V val;
long expirationTime;
}

Map<K, ValueWithExpiration>

ttl => expirationTime
  • follow up:

    When get/put expirationTime?

    Map => linear scan ? => PriorityQueue

LeetCode | Intersection of Two Arrays

发表于 2018-02-02   |   分类于 Leetcode   |     |   阅读次数

§349. Intersection of Two Arrays

Note:

  • Each element in the result must be unique. -> use set
  • The result can be in any order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//java
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null)
return null;
if (nums1.length == 0 || nums2.length == 0)
return new int[0];
Set<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < nums1.length; i++) {
hs.add(nums1[i]);
}
Set<Integer> res = new HashSet<Integer>();

for(int i = 0;i < nums2.length;i++){
if (hs.contains(nums2[i])) {
res.add(nums2[i]);
hs.remove(nums2[i]);
}
}
int[] res_ = new int[res.size()];
int i = 0;
for (Integer num : res) {
res_[i++] = num;
}
return res_;
}
/*
Using Stream in java 8
Set<Integer> set = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
return Arrays.stream(nums1).distinct().filter(e-> set.contains(e)).toArray();
*/

1
2
3
4
5
6
7
8
9
//c++
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> s(nums1.begin(), nums1.end());
vector<int> ans;
for (int num : nums2)
if (s.erase(num))
ans.push_back(num);
return ans;
}

§Follow up

  • If sorted?
    1. Use 2 pointers. O(M+N)
    2. Binary search. O(MlogN) or O(NlogM)

§350. Intersection of Two Arrays II

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//java
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
for (int i = 0; i < nums1.length; i++){
if (map.containsKey(nums1[i]))
map.put(nums1[i],map.get(nums1[i])+1);
else
map.put(nums1[i],1);
}
for (int i = 0; i < nums2.length; i++){
if (map.containsKey(nums2[i]) && map.get(nums2[i]) > 0){
res.add(nums2[i]);
map.put(nums2[i],map.get(nums2[i])-1);
}
}
int[] res_ = new int[res.size()];
int i = 0;
for (Integer num : res)
res_[i++] = num;
return res_;
}
1
2
3
4
5
6
7
8
//java 8 using Strem
Map<Integer, Long> map = Arrays.stream(nums2).boxed().collect(Collectors.groupingBy(e->e, Collectors.counting()));
return Arrays.stream(nums1).filter(e ->{
if(!map.containsKey(e)) return false;
map.put(e, map.get(e) - 1);
if(map.get(e) == 0) map.remove(e);
return true;
}).toArray();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Another solution in C++
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
int n1 = nums1.size(), n2 = nums2.size();
int i = 0, j =0;
vector<int> ans;
while (i<n1 && j<n2){
if (nums1[i]==nums2[j]){
ans.push_back(nums1[i]);
i++,j++;
}
else if (nums1[i]>nums2[j])
j++;
else
i++;
}
return ans;
}

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?

    Use 2 pointers, O(M+N)

  • What if nums1’s size is small compared to nums2’s size? Which algorithm is better?

    Use the smaller array to construct the counter hash.

  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

    Divide and conquer.

    Do repeatedly: Slice nums2, caculate intersections, write partial results back to the memory.

Java console in Sublime Text

发表于 2018-01-31   |   分类于 Program   |     |   阅读次数
  1. Tools -> Build System -> New Build System…
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"shell_cmd": "javac \"$file\"",
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",

"variants":
[
{
"name": "Run",
"shell_cmd": "java $file_base_name"
}
]
}
  1. Save as JavaC.sublime-build

  2. Choose Automatic, run using command + B

1
2
var fName = function(fVal) {}; 
console.log(fName(fVal));

§Delete build system

1
OS X: ~/Library/Application Support/Sublime Text 3/Packages/

X1_Binary Search Tree

发表于 2018-01-31   |   分类于 Program , Leetcode   |     |   阅读次数

§Binary Search Tree

§Reference

Binary Search Tree | Set 1 (Search and Insertion)

Github | X1_Binary Search Tree

§Definition

  1. left subtree < root < right subtree

  2. no duplicate nodes

    • What if duplicate? add “count” attribution

    • self-balance: almost full tree. Using red-black tree

    • worst case:

    • 1
      2
      3
      4
      5
      6
      7
      1\2\3\4\5\6
      or
      1
      2
      3
      4
      5/6 7\8
  3. ​

§Coding

• https://leetcode.com/problems/find-k-closest-elements

• https://leetcode.com/problems/closest-binary-search-tree-value

• https://leetcode.com/problems/closest-binary-search-tree-value-ii

• https://leetcode.com/problems/binary-tree-level-order-traversal

• https://leetcode.com/problems/maximum-depth-of-binary-tree

• https://leetcode.com/problems/balanced-binary-tree

• https://leetcode.com/problems/search-in-rotated-sorted-array

• https://leetcode.com/problems/search-in-rotated-sorted-array-ii

####Note

  1. 先定signature

  2. 库函数Arrays.binarySearch(arr, x),not found: < 0

  3. java8 Collectors

  4. 1
    private static final double EPSILON = 1e-10;
  5. boilerplate模版

  6. 主动测试test case

  7. 1
    Queue<T> q = new LinkedList<>();
  8. IterativeInOrder, Pre, Post

§Q

  • 360.Sort Transformed Array

    a > 0,

    binary search find the closest one with -b/2a, then …

    Or from l & r -> middle

  • 173.Binary Search Tree iterator

123
Zoey HAN

Zoey HAN

CS | Web | Write | Music

30 日志
12 分类
21 标签
GitHub Weibo facebook csdn
© 2016 - 2019 Zoey HAN
由 Hexo 强力驱动
主题 - NexT.Pisces