Monday, October 26, 2015

Leetcode: Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.
For example,
   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.











------------------------------------------
------------------------------------------
Using two pointers: late, pre:
pre goes forward for n steps then move both pointers forward until pre reaches the end. Then the late is the location we want. There are two cases in this method, when in the final, the late is the first node and when late is non-first node:
/////////////////////////////////////////////////
//codes
class Solution {
public:
       ListNode* removeNthFromEnd(ListNode* head, int n) {
              //check input
              if (head == NULL)return head;
              ListNode *pre = head, *late = head;
              //move the pre n node ahead
              for (int i = 0; i<n &&pre != NULL; i++){
                     pre = pre->next;
              }
              //if the head would be deleted
              if (pre == NULL) {
                     head = head->next;
                     delete late;
                     return head;
              }
              //move two pointer forward with n interval
              while (pre->next != NULL){
                     pre = pre->next;
                     late = late->next;
              }
              //delete the the one in late->next
              pre = late->next->next;
              delete late->next;
              late->next = pre;
              return head;
       }
};




Leetcode: H-Index

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
Show Hint 
    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
    Hide Tags
     Hash Table Sort
    Hide Similar Problems
     (M) H-Index II
















    -----------------------------------------------------------
    ----------------------------------------------------------
    Sort and check, that's all for a convenient way. 
    To reduced the time, we don't need to sort the whole array, we can sort one then check one. E.g.,when using bubble sort, we can find out the minimal one then check the h value, find the next minimal value then check the h value, ......., until the real h is found. If no is found, then h=0. The testing results highly depend on the testing case. 
    e.g. 
    1    2    2     3     3   citations 
    5   4     3     2     1   potential H index

    check from left to right, when citation[i]>=potential[i], return length-i. 

    OR
    e.g. 
    1    2    2     3     3   citations 
    1   2     3     4     5   potential H index

    check from right to left, when citation[i]>=potential[i], return i. 



    ///////////////////////////////////////////////
    //code
    class Solution {
    public:
           int hIndex(vector<int>& citations) {
                  //check input
                  int len = citations.size();
                  //if (len==0) return 0;
                  //bubble sort and judge
                  for (int i = 0; i<len; i++){
                         for (int j = len - 1; j>i; j--){
                               if (citations[j]<citations[j - 1]) swap(citations[j], citations[j - 1]);
                         }
                         //judge h
                         if (citations[i] >= len - i)return len - i;
                  }
                  return 0;
           }
    };



    Sunday, October 25, 2015

    Leetcode: Reorder List

    Given a singly linked list L: L0→L1→…→Ln-1→Ln,
    reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
    You must do this in-place without altering the nodes' values.
    For example,
    Given {1,2,3,4}, reorder it to {1,4,2,3}.
    Hide Tags
     Linked List








    -----------------------------------------------------------------
    As the pointer of list can't move backward, double pointers method scan from two end to the center doesn't work. So we need to think about way to do it with an forward direction. Following is one of such method:
    1. locate the middle of the list: 
        there are two kinds, odd and even number of nodes, the middle one should be calculated differently. 
    2. reverse the order for all the nodes in right side of middle node. For how to reverse the whole linked list, check there. 
    3. merge the list with forward order. 
    when number of node is even, the procedure is shown below:

    when number of node is odd, the procedure is shown as:



    ////////////////////////////////////////////////
    ////code
    class Solution {
    public:
           void reorderList(ListNode* head) {
                  //check input
                  if (head == NULL || head->next == NULL || head->next->next == NULL) return;
                  //find the middle and final location
                  int len = 1, midLen = 0;
                  ListNode *mid = head, *final = head, *tmp = head, *left = head;
                  while (mid->next != NULL) { len++; mid = mid->next; }
                  final = mid;
                  mid = head;
                  //locate the mid
                  midLen = (len % 2) == 1 ? len / 2 + 1 : len / 2;
                  for (int i = 1; i<midLen; i++){
                         mid = mid->next;
                  }
                  tmp = mid;

                  //reverse the right half list
                  ListNode* cur = tmp->next;
                  ListNode* pre = cur->next;
                  cur->next = NULL;//the final node after reverse
                  while (pre != NULL)
                  {
                         ListNode* temp = pre->next;
                         pre->next = cur;
                         cur = pre;
                         pre = temp;
                  }
                  tmp->next = cur;

                  //reorder the list
                  mid = tmp;
                  for (int i = 1; i <= len - midLen; i++){
                         tmp = left->next;
                         left->next = mid->next;
                         mid->next = mid->next->next;
                         left->next->next = tmp;
                         //update pointers
                         left = left->next->next;
                         if (left == mid)break;
                  }
                  return;
           }
    };






    Algorithm: reverse the whole liked list

    e.g., list=1->2->3->4->null

    reverse it to: 4->3->2->1->Null;

    -------------------------
    1. The procedure is shown below:
    using three pointers: cur, pre and tmp. As following example shown, in the first step, put 2 in front of 1, then put 3 in front of 2, ........ until all are reversed. 





    2. Note the case when only one node exist. In such a case, "temp = pre->next;" will be wrong! So this line of code should be within the while loop as the codes shown below. 
       


    //////////////////////////////////
    //code
    class Solution {
    public:
           ListNode* reorderList(ListNode* head) {

                  // reverse the link list
                  //ListNode *dum = new ListNode(-1);
                  //dum->next = head;
                  ListNode* cur = head;
                  ListNode* pre = head->next;
                 
                  cur->next = NULL;//the final node after reverse
                  while (pre != NULL)
                  {
                         ListNode* temp = pre->next;
                         pre->next = cur;
                         cur = pre;
                         pre = temp;
                  }
                  head = cur;
                  return head;
           }
    };

    Saturday, October 24, 2015

    Leetcode: Insert Interval

    Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
    You may assume that the intervals were initially sorted according to their start times.
    Example 1:
    Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
    Example 2:
    Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
    This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
    Hide Tags
     Array Sort
    Show Similar Problems












    ----------------------------------------------------------------------------------
    Basically there are three cases in this implementation. see the plot below: 

    case 1 and 2 are easy as no merge occurs. but for case two, there are overlapping with each other. In case two, there are also there sub-classes, but we can classify all these sub-classes into one but using the the judgement: s1, s2 and s3 are all <=e &&  e1, e2 and e3 are all >=s. this can simplify the procedure. 

    So in the codes:
    1. when meet case 1 and 3, insert the intervals[i] directly;
    2. when meet case 2, on insertion is needed, but the newInterval  should be updated with new boundaries when compared to the intervals[i];
    ///////////////////////////
    //codes
    class Solution {
    public:
           vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
                  vector<Interval> ret;
                  bool isInsert = false;
                  for (int i = 0; i<intervals.size(); i++) {
                         // already insert newInterval
                         if (isInsert) {
                               ret.push_back(intervals[i]);
                               continue;
                         }

                         // insert newInterval before current interval
                         if (newInterval.end < intervals[i].start) {
                               ret.push_back(newInterval);
                               ret.push_back(intervals[i]);
                               isInsert = true;
                               continue;
                         }

                         // combine newInterval with current interval
                         if (newInterval.start <= intervals[i].end && intervals[i].start <= newInterval.end) {
                               newInterval.start = min(newInterval.start, intervals[i].start);
                               newInterval.end = max(newInterval.end, intervals[i].end);
                               continue;
                         }

                         // newInterval after current interval
                         ret.push_back(intervals[i]);
                  }

                  if (!isInsert) ret.push_back(newInterval);
                  return ret;
           }
    };