Thursday, October 15, 2015

algorithms: merge sort

Merge Sort:

It uses divide and conquer method to simplify the problem. It has O(nlgn) running time in general, even in worst case. But it introduces extra memory to do the sorting (as it needs a tmp vector to temparally store the input vector). When using back tracking, the space efficiency is not so good compared with quick sort.

The general algorithm is shown below:


An example is shown below:



/////////////////////////////////////////////////////////////////////////
//codes:
class Solution {
public:
       // s[first, last] -- is part of the data in s that needs to be sorted.
       vector<int> MergeSort(vector<int> s, int first, int last)
       {
              //devide s into two halves
              if (last - first > 0){//more than 2 elements
                     s = MergeSort(s, first, (first + last) / 2);
                     s = MergeSort(s, (first + last) / 2+1, last);
                     //merge the two halves into one
                     vector<int> tmp=s;
                     int i = first, j = (first + last) / 2 + 1, k=first;
                     while ( i <= (first + last) / 2 || j <= last){ //at least one half is not empty
                           if (i>(first + last) / 2) s[k++] = tmp[j++]; //i is out of bound
                           else if (j>last) s[k++] = tmp[i++];  //j is out of bound
                           else if (tmp[i] <= tmp[j]) s[k++] = tmp[i++];
                           else s[k++] = tmp[j++];
                     }
              }
              else {//only one element
                     ;
              }
              return s;
       }
};

Algorithms: Quick sort

Quick Sort:

In general, quick sort has O(nlgn) running time, but in worst case, it's about O(n^2). One advantage of this sort is that it uses only exchange elements inside to realize the sort. In this way, it's able to sort without introducing extra memory, or the space consumption could be lower to O(1)--strictly speaking, cause backtracking is used, the stack usage is not O(1).

The general procedure is listed below (back tracking is used):
The detailed example is shown below:






/////////////////////////////////////////////////////////////////////
//codes
class Solution {
public:
       // s[first, last] -- is part of the data in s that needs to be sorted.
       vector<int> QuickSort(vector<int> s, int first, int last)
       {
              int lower = first + 1, upper = last, bound = s[(last + first) / 2];
              //put the bound (middle one) in the first place
              //to ensure that it's not moved around. Later it
              //will be moved back
              swap(s[first],s[(last+first)/2]);
              //swap according to bound
              while (lower <= upper){
                     while (s[lower] < bound){
                           lower++;
                     }
                     while (s[upper] > bound){
                           upper--;
                     }
                     if (lower < upper) swap(s[lower++], s[upper--]);
                     else lower++;
              }
           //move bound back to it's proper position
           swap(s[first], s[upper]);
              //partition and call quicksort, the previous bound is not counted in.
              if (first < upper - 1) s=QuickSort(s, first, upper-1);
              if (upper + 1 < last) s=QuickSort(s, upper + 1, last);
        return s; //up to now, the input s has been sorted!
       }

};



Tuesday, October 13, 2015

Leetcode: Reverse a singly linked list (8ms)

Reverse a singly linked list.
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
--------------------------------------------------
-------------------------------------------------
1. create a dummy node and connects to head
2. insert the following nodes after dummy node one by one
This way we don't need to go through the whole list in head to get the final node. The logic is simple and easy to follow:

////////////////////////////////////////////////////////////
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        //check input
        if(head==NULL || head->next==NULL)return head;
        ListNode *dummy= new ListNode(-1), *pre, *later;
        dummy->next=head;
        pre=head->next;
        later=pre->next;
        while(1){
            //insertion
            pre->next=dummy->next;
            dummy->next=pre;
            //check loop //NOTE: should check before updating points
            if(later==NULL)break;            
            //update pointers
            pre=later;
            later=pre->next;
        }
        head->next=NULL;//clear the tail
        return dummy->next;
    }
};

Monday, October 12, 2015

algorithm: Bubble sort

Bubble sort:

Scan from bottom to top, put lighter element up.

/////////////////////
class Solution {
public:
       vector<int> BubbleSort(vector<int> s)
       {
           //implement the bubble sort
              int sLen=s.size();
              for (int i = 0; i < sLen; i++){
                     for (int j = sLen - 1; j > i; j--){
                           if (s[j] < s[j - 1]) swap(s[j],s[j-1]);
                     }
              }
              return s;
       }
};

Algorithm: Insertion sort

Insertion sort:

Insert the current data into a proper position of the sorted array.

Running time is around O(n^2).

/////////////////////////
#include "stdafx.h"
# include <cstdlib>
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector
# include <map>         // std::map
# include <unordered_map>
# include <string>
#include <bitset>
#include <ctype.h>
using namespace std;


class Solution {
public:
       vector<int> InsersionSort(vector<int> s)
       {
           //implement the insersion sort
              int i, j, tmp,sLen=s.size();
              for (i = 1; i < sLen; i++){
                     tmp = s[i];
                     j = i;
                     while (j>0 && tmp < s[j - 1]){
                           s[j] = s[j - 1];
                           j--;
                     }
                     s[j] = tmp;
              }
              return s;
       }
};


int main(int argc, char *argv[])

{
       vector<int> inp = { 3, 4, 1};
       Solution s;
       vector<int> l = s.InsersionSort(inp);

}


Friday, October 9, 2015

Leetcode: Swap Nodes in Pairs (4ms)

problem
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Hide Tags
 Linked List
Show Similar Problems








------------------------
-----------------------

1. create a dummy node for head
2. exchange two nodes

class Solution {
public:
       ListNode* swapPairs(ListNode* head) {
              //check input
              if (head == NULL) return NULL;//empty list node  
              if (head->next == NULL) return head; // one list node
              ListNode* t1, *t2, *t3, *tmp, *pre = new ListNode(-1);
              pre->next = head;
              t1 = head;
              head = pre;
              while (1){
                     if (t1->next != NULL){
                           //keep previous value
                           t2 = t1->next;
                           t3 = t2->next;
                           //exchange two nodes
                           tmp = t2;
                           tmp->next = t1;
                           tmp->next->next = t3;
                           //connect to prevous node
                           pre->next = tmp;
                           //prepare for next loop
                           pre = t1;
                           t1 = t3;
                           if (t3 == NULL || t3->next == NULL) break;
                     }
              }
              return head->next;
       }
};

Friday, September 4, 2015

Leetcode: Contains Duplicate II (hash table)

PROBLEM:

https://leetcode.com/problems/contains-duplicate/

Using map and need to keep a windom with the maximal length of k.

//////////////////////////////////////////
//code

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (k == 0 || nums.size() == 0)return false;
unordered_map<int, int> tmp;

//check the input
int pre = 0;
if (nums.size() == 0)return false;
for (int i = 0; i<nums.size(); i++){
tmp[nums[i]] = i;
if (pre == tmp.size())return true;
else pre = tmp.size();
//remove the first item from map
if (tmp.size() == k + 1){
tmp.erase(tmp.begin());
pre--;
}

}
return false;
}
};