Sunday, June 5, 2016

Iterator

Iterator, an interface in java.util for iterating sequence of objects.
public interface Iterator {
    boolean hasNext();
    Object next();
    void remove();                          // The remove() method is optional.
  }

An Iterator is like a bookmark.
 Just as you can have many bookmarks in a book, you can have many Iterators iterating over the same data structure, each one independent of the others.

One Iterator can advance without disturbing other Iterators that are iterating over the same data structure.
The first time next() is called on a newly constructed Iterator, it returns the first item in the sequence. Each subsequent time next() is called, it returns the next item in the sequence.
 After the Iterator has returned every item in the sequence, every subsequent call to next() throws an exception and halts with an error message. (I find this annoying; I would prefer an interface in which next() returns null. The Java library designers disagree.)

To help you avoid triggering an exception, hasNext() returns true if the Iterator has more items to return, or false if it has already returned every item in the sequence. It is usually considered good practice to check hasNext() before calling next(). (In the next lecture we'll learn how to catch exceptions; that will give us an alternative way to prevent our program from crashing when next() throws an exception.)

 There is usually no way to reset an Iterator back to the beginning of the sequence. Instead, you construct a new Iterator.

Most data structures that support Iterators "implement" another interface in
java.util called "Iterable".
public interface Iterable {
    Iterator iterator();
  }

怎么用,一般来说,如果想遍历一个数据结构DS,就call DS.iteratre(); 这个method会constructs and returns DSIterator whose fields are initialized so it is ready to return the first item in DS.

例子:
/* list/SListIterator.java */

package list;
import java.util.*;

public class SListIterator implements Iterator {
  SListNode n;

  public SListIterator(SList l) {
    n = l.head;
  }

  public boolean hasNext() {
    return n != null;
  }

  public Object next() {
    if (n == null) {
      /* We'll learn about throwing exceptions in the next lecture. */
      throw new NoSuchElementException();                       // In java.util
    }
    Object i = n.item;
    n = n.next;
    return i;
  }

  public void remove() {
    /* Doing it the lazy way.  Remove this, motherf! */
    throw new UnsupportedOperationException("Nice try, bozo."); // In java.lang
  }
}

/* list/SList.java */

package list;
import java.util.*;

public class SList implements Iterable {
  SListNode head;
  int size;

  public Iterator iterator() {
    return new SListIterator(this);
  }

  [other methods here]
}

Tuesday, May 17, 2016

Ruby on Rails

Tools:
 Rake - Create/migrate database, clear web session data.
 WEBrick - Web server for hosting Rails web applications.
 SQLite - A simple database system.
 Rack Middleware - Standardized interface for interaction between web server and web application.

rails new hello_www
cd hello_www
rails server (start a web server)

Under hello_www (Rails root):
app: models, views, and controllers code
bin: helper scripts (bundle, rails, rake)
config: App, database and route configuration
db: database schema and migrations
Gemfile: specify the required gems
lib:
log: application logging directory
pulic: webroot of the application
test: Tests - Agile development





Popular web application frameworks

- Ruby on Rails (Ruby)
- Play (Java and Scala)
- ASP.NET MVC (Microsoft)
- Django (Python)
- Sinatra (Ruby) (very light-weight)
- Symfony (PHP)
- Sails.js (Node.js, JavaScript)

Content management systems (CMSs):
WordPress, Drupal, Joomla!

The MVC Design pattern
Model-View-Controller model
 - Decouples data (model) and presentation (view)
 - A controller handles requests, and coordinates between the model and the view
 - More robust applications, easier to maintain

MVC control flow:
 1. User interface (view) awaits user input
 2. User provides input, e.g., clicks a button
 3. Controller handles the input event -> some action (handler or callback) understandable by the model
 4. Controller notifies the model, possibly changing the model's state
 5. Controller notifies the view (if it needs to be updated). Back to step 1.


Tuesday, May 10, 2016

PriorityQueue

Operations:
add O(logn), find largest O(1), remove largest O(log(n))

Application:
scheduling long streams of actions to occur at various future times.
useful for sorting.

Common implementation is Heap.

Heap:
max-heap is a binary tree that:
Both labels in both children of each node are less than node's label

So node at the top has largest label.

Tuesday, April 26, 2016

Longest Increasing Subsequence

Leetcode 300
Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
O(n^2):
Naive solution is use array T[] to track the LIS for each element in the original array. We have to track all the elements because the LIS can only increase for previous element which are smaller than current element.
public class Solution {
    public int lengthOfLIS(int[] nums) {
        // naive solution, keep another array to store the LIS so far. O(n^2)
        if (nums==null || nums.length == 0) return 0;
        int[] lens = new int[nums.length];
        int maxsofar = 1;
        for (int i = 0; i < nums.length; i++) {
            lens[i] = 1;
        }
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    if ((lens[j]+1) > lens[i]) {
                        lens[i] = lens[j] + 1;
                    }
                }
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (lens[i] > maxsofar) maxsofar = lens[i];
        }
        return maxsofar;
    }
}

Tuesday, March 29, 2016

Best Time to Buy and Sell Stock


  1. Best Time to Buy and Sell Stock
Leetcode 121 (M)
只能买卖一次。
只能一次的话,就是要寻找最小和最大的值(同时必须满足最大值在最小值后面)
可以用两个值来存,maxcurr记录对于第i天可以拿到的最大利润,maxsofar记录到目前为止见过的最大利润(最大的maxcurr)。
所以唯一的问题是如何计算maxcurr,如果maxcurr小于0,那么就是0,对于第i天的maxcurr来说,如果maxcurr + (p[i] - p[i-1]) > 0, 那么更新maxcurr。

或者可以,一直寻找最小的minprice,然后用prices[i]-minprice,同时即时更新minprice。

code1:
public class Solution {
    public int maxProfit(int[] prices) {
        int maxcurr = 0;
        int maxsofar = 0;
        for (int i = 1; i < prices.length; i++) {
            maxcurr = Math.max(0, maxcurr + (prices[i] - prices[i-1]));
            maxsofar = Math.max(maxsofar, maxcurr);
        }
        return maxsofar;
    }
}

code2:
public int maxProfit(int[] prices) {
    int profit = 0;
    int minElement = Integer.MAX_VALUE;
    for(int i=0; i < prices.length; i++){
       profit = Math.max(profit, prices[i]-minElement);
       minElement = Math.min(minElement, prices[i]);
    }
    return profit;
}
  1. Best Time to Buy and Sell Stock II
Leetcode 122 (M)
可以买卖多次。这样的话很容易理解,就是把所以递增的都增量都加起来就可以了。因为如果是递增,那么price[j] - price[k] = price[j]-price[i] + price[i]-price[k]

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }
        
        int total = 0;
        
        for (int i = 1; i < prices.length; i++) {
            total += Math.max(0, prices[i] - prices[i-1]);
        }
        return total;
    }
}
  1. Best Time to Buy and Sell Stock III
  2. Best Time to Buy and Sell Stock IV
  3. Best Time to Buy and Sell Stock with Cooldown

Dynamic Programming

Dynamic programming is a technique for solving problems with the following properties:
  1. An instance is solved using the solutions for smaller instances.
  2. The solution for a smaller instance might be needed multiple times.
  3. The solutions to smaller instances are stored in a table, so that each smaller instance is solved only once.
  4. Additional space is used to save time.
经典题目:
1. 买卖股票I II III IV