Thursday, October 22, 2015

Leetcode: Sort List

Problem:

Sort a linked list in O(n log n) time using constant space complexity.
Hide Tags
 Linked List Sort
Show Similar Problems




--------------------------------------------
1. O(nlogn) sort:  only merge sort, heap sort and quick sort can achieve this goal. But all of them are using recursion, and therefore they are using non-constant space. So we need to do some modifications on them, e.g., we can use iteration to take place the recursion. 
For quick sort, the iteration doesn't work. But for merge sort, it's possible to use recursion. the general idea can be seen below:
we can do recursion one by one in each interval loop. 
In the original merge sort algorithm, when merge two halves into one, we need to create the third vector to temporally store the merged values. This will introduce extra space usage and not constant space. Here we using a method to do merging two halves into one without introducing an additional space: 
here we use an example when interval=2:



/////////////////////////////////////////////////////
//codes
class Solution {
public:
       ListNode* sortList(ListNode* head) {
              //check input
              if (head == NULL || head->next == NULL)return head;
              //dummy node
              ListNode *dum = new ListNode(-1);
              dum->next = head;
              ListNode *upHead = dum, *downHead = dum;
              ListNode *tmp = NULL;
              //get the number of nodes
              int len = 0;
              while (head != NULL){
                     len++;
                     head = head->next;
              }
              //outter loop for sort with diff. intervals
              for (int interval = 1; interval < len; interval = interval * 2){
                     //clear pointers
                     upHead = dum;
                     downHead = dum;

                     //locate the downHead for the first run
                     for (int j = 0; j < interval; j++){
                           downHead = downHead->next;
                     }
                     //check loop stop condition
                     if (downHead->next == NULL)break;
                     //inner loop
                     for (int i = 1;; i++){
                           //check loop stop condition
                           if (downHead->next == NULL)break;
                           int countDownHead = 0;
                           //sort the two half lists
                           while (countDownHead<interval){
                                  //check loop stop condition
                                  if (downHead->next == NULL || upHead == downHead)break;

                                  if (upHead->next->val>downHead->next->val){
                                         tmp = upHead->next;
                                         upHead->next = downHead->next;
                                         downHead->next = downHead->next->next;
                                         upHead->next->next = tmp;

                                         //update upNode
                                         upHead = upHead->next;
                                         countDownHead++;//count downHead was moved for how many times
                                  }
                                  else{
                                         upHead = upHead->next;
                                         //if (upHead == downHead)break;
                                  }
                           }


                           //locate the downHead to the end of previous run
                           for (int j = 0; j < interval - countDownHead; j++){
                                  if (downHead == NULL || downHead->next == NULL)break;
                                  downHead = downHead->next;
                           }
                           upHead = downHead;
                           //locate the downHead to the begin of next run
                           for (int j = 0; j < interval; j++){
                                  if (downHead == NULL || downHead->next == NULL)break;
                                  downHead = downHead->next;
                           }
                     }
              }
              head = dum->next;
              delete dum;
              return head;
       }
};



Monday, October 19, 2015

Leetcode: Maximum Gap (16ms)

PROBLEM:
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
------------------------------------------------------
------------------------------------------------------
Using bucket sort.
assign the value one by one to the related bucket with index 'id'= (x-min)/ave_gap;
it's possible a bucket contain more than 2 values, only keep the minimal and maximal value. 
////////////////////////////////////////////////////////////
//CODES
class Solution {
public:
       int maximumGap(vector<int>& nums) {
              //check input
              if (nums.size() == 0 || nums.size() == 1) return 0;
              //find out the min and max
              int Min = nums[0], Max = nums[0];//Min=INT_MAX, Max=INT_MIN;
              for (auto x : nums){
                     Min = Min<x ? Min : x;
                     Max = Max>x ? Max : x;
              }
              //gap, take ceiling
              int gap = ceil((Max - Min) / (nums.size() - 1))+1;
              //put to buckets
              vector<vector<int>> buckets(nums.size() - 1);
              for (auto x : nums){
                     int idx = (x - Min) / gap;//get index for buckets
                     if (buckets[idx].empty()){
                           buckets[idx].reserve(2);
                           buckets[idx].push_back(x);
                           buckets[idx].push_back(x);
                     }
                     else{
                           if (x < buckets[idx][0]) buckets[idx][0] = x;
                           if (x > buckets[idx][1]) buckets[idx][1] = x;
                     }
              }
              //find max gap
              int pre = 0, cur = 0, mgap = 0;
              if (buckets.size()>1){
                     for (int i = 1; i<buckets.size() ; i++){
                           if (buckets[i].empty()) continue;
                           cur = buckets[i][0];
                           mgap = cur - buckets[pre][1]>mgap ? cur - buckets[pre][1] : mgap;
                           pre = i;
                           //if (buckets[i][1] == Max)break;
                     }
              }
              else{
                     mgap = buckets[0][1] - buckets[0][0];
              }
              return mgap;
       }
};

Saturday, October 17, 2015

Leetcode: Sort a linked list using insertion sort

Problem:
Sort a linked list using insertion sort.
Hide Tags
 Linked List Sort
Show Similar Problems






---------------------------------------
---------------------------------------
1. create a dummy node to function as the head when sorting, otherwise, head will be moved when sorting.

2. insertion sort performs from bottom to top in the second loop. Refer to here for insertion sort. But in listed nodes, move from bottom to top is impossible. So, we need to scan from top to down in the second loop.

3. operations about how to insert a node into a list. The pointer p in the outer loop should be update or should be move a step forward in each loop. But note that this move is not needed when a insertion occurs. see codes for details.




///////////////////////////////////////////////////
// codes
class Solution {
public:
       ListNode* insertionSortList(ListNode* head) {
              //check input
              if (head == NULL || head->next == NULL) return head;
              //create dummy node
              ListNode *dum = new ListNode(-1);
              dum->next = head;
              ListNode *p = head, *pScan = dum, *tmp = head;
              //sort
              while (p->next != NULL){
                     pScan = dum;
                     while (p->next != NULL){
                           if (pScan->next->val > p->next->val){
                                  //insertion; when insertion, don't need update p
                                  tmp = pScan->next;
                                  pScan->next = p->next;
                                  p->next = pScan->next->next;
                                  pScan->next->next = tmp;
                                  break;
                           }
                           else if (pScan == p){
                                  //uppdate p
                                  p = p->next;
                                  break;
                           }
                           pScan = pScan->next;
                     }

              }
              head = dum->next;
              delete dum;
              return head;
       }

};

Friday, October 16, 2015

Leetcode: Largest Number (sort)

Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.

----------------------------------------
----------------------------------------
1. using string type of x+y>y+x to decide the order of x and y. If x+y>y+x is true, x should be put in front; If not, y should be put in front. Here a self made sort function is used. 
2. then concatenate the string together
/////////////////////////////////
//code
class Solution {
public:
       //self made comparison 
       static bool comp(int a, int b){
              string x = to_string(a), y = to_string(b);
              return x + y>y + x;
       }

       string largestNumber(vector<int>& nums) {

              //sort the nums according to above comparison 
              sort(nums.begin(), nums.end(), comp);
              //convert to string
              string res = "";
              for (int i = 0; i<nums.size(); i++){
                   res += to_string(nums[i]);//concatenate the string
              }
              if (res[0] == '0') res = '0';
              return res;
       }

};