2016年2月10日 星期三

LEET code -- Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3


這題要去把圖畫出來才明顯
我們只要管root在哪裡   在看他左右個剩下幾個點   就可以知道它下面可以怎麼變化

number of BSTs with k being the root 
= count of BSTs of k-1 consecutive numbers * count of BSTs of n-k consecutive numbers





 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
int numTrees(int n) {
    //tree[0]=with 0 tree has only 1 bts
    //tree[1]=with 1 tree node and have 1 bts
    //tree[2]=with 2 node, and 2 bts
    //tree[3]=with 3 ndoe, has 5 bts
    /*
    v
    1 2 3 4 5-->2~5 is the tree[4]
      V
    1 2 3 4 5-->1 is three[1],3~5 is tree[3]
        V
    1 2 3 4 5-->1~2 is tree[2],4~5 is tree[2]
    
    therefore, we can cacaluate the result
    
    */
    int tree[n+1];
    tree[0]=1;
    tree[1]=1;
    
    for(int i=2;i<=n;i++){
        int sum=0;
        for(int j=1;j<=i;j++){
            sum+=tree[j-1]*tree[i-j];
        }
        tree[i]=sum;
    }
    return tree[n];
}

LEET code -- Find the Duplicate Number

 Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:


  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

這題要利用link list cycle II 的解法
因為這個陣列只包含1~n  
所以可以看成是圖型   第0個點 下一點要去哪




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
int findDuplicate(int* nums, int numsSize) {
    //like link list cycle
    int slow=0,fast=0;
    while(true){
        int slowindex=slow,fastindex=fast;
        slow=nums[slowindex];
        fast=nums[nums[fastindex]];
        //printf("A%d %d,%d %dA",slow,slowindex,fast,fastindex);
        if(slow==fast)break;
    }
    int find=0;
    while(true){
        find = nums[find];
        slow = nums[slow];
        if(find==slow)return find;
    }
}

2016年2月7日 星期日

LEET code -- Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...

要注意24行 要把ri->next變成NULL
不然無限迴圈



 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
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* oddEvenList(struct ListNode* head) {
    if(head==NULL)return NULL;
    struct ListNode* righthead=head->next;
    struct ListNode* lefthead = head;
    struct ListNode* le=head;
    struct ListNode* ri=head->next;

    while(le->next!=NULL && ri->next!=NULL){
        if(ri->next!=NULL){
            le->next=ri->next;
            le=ri->next;
        }
        if(le->next!=NULL){
            ri->next=le->next;
            ri=le->next;
        }else{
            ri->next=NULL;
        }
        
    }    
    //printf("aa");
    le->next=righthead;
    return head;
}

LEET code -- Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.




這是recursive的版本
iterative 可以參考preorder


 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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    //int size=*returnSize;
    if(root==NULL)return NULL;
    int lesize=0,risize=0,*le=NULL,*ri=NULL;
    le=inorderTraversal(root->left,&lesize);
    ri=inorderTraversal(root->right,&risize);
    
    
    int *ans=malloc(sizeof(int)*(lesize+1+risize));
    *returnSize = lesize+1+risize;
    for(int i =0;i<lesize;i++){
        if(le!=NULL)ans[i]=le[i];
    }
    ans[lesize]=root->val;
    for(int j=0;j<risize;j++){
        if(ri!=NULL)ans[lesize+1+j]=ri[j];
    }
    return ans;
}

2016年2月6日 星期六

LEET code --Lowest Common Ancestor of a Binary Search Tree

 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

這題解法用兩個狀態來代表  如果-1 代表底下沒有目標
如果0代表有找到
如果都找到了  就把pointer記錄在ans

但是要注意  因為我要記錄的是 pointer的位置  所以必須要用double pointer
所以在30行的 *ans=root
就會把在11行的temp指向root裡面紀錄的記憶體位置




關於pointer的關係 可以看
http://wp.mlab.tw/?p=176




 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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    struct TreeNode a;
    struct TreeNode *temp=&a;
    struct TreeNode** ans=&temp;//(struct TreeNode*)malloc(sizeof(struct TreeNode**));
    parse(root,p,q,ans);
    printf("ans=%d, root=%d",(*ans)->val,root->val);
    return *ans;
    
}

int parse(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q, struct TreeNode** ans ){
    int anscount=0;
    if(root==NULL)return -1;
    if(root->val ==p->val || root->val==q->val)anscount++;
    //printf("root:%d p=%d q=%d, ans=%d ",root->val,p->val,q->val,anscount);
    int le = parse(root->left,p,q,ans);
    int re = parse(root->right,p,q,ans);
    if(le==0 )anscount++;
    if(re ==0)anscount++;
    if(anscount>=2){
        printf("ans=%d",(*ans)->val);
        *ans=root;
        printf("root=%d, ans=%d ",root->val,(*ans)->val);
        return -1;
    }else return anscount-1;
}
-------------
上面的太冗了

如果左邊有檢查到  但是右邊都沒有  那代表p q都集中在左邊


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(root==NULL)return NULL;
    if(root == p || root==q)return root;
    
    struct TreeNode* le=lowestCommonAncestor(root->left,p,q);
    struct TreeNode* ri=lowestCommonAncestor(root->right,p,q);
    
    if(le && ri)return root; //both of the le and ri have value==> lowest
    
    if(le)return le;//only re have value
    else return ri;//only ri have value
}
----------
因為是BST
所以 root的左邊都是小於root的

而LST 是找  q<=lst<=p
因此可以簡單的while跑完

 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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    //because it is a bst ans assume p<=q
    //so the lst must be p<=lst<=q
    // therefore, is the current root<p -->the lst must be higher lst(root->right,p,q)
    //root>q -->the lst must be lowwer lst(root->left,p,q)
    
    if(p->val > q->val){
        struct TreeNode* temp=q;
        q=p;
        p=temp;
    }
    struct TreeNode * lst=root;
    while(true){
        if( lst->val < p->val)lst=lst->right;
        else if(lst->val > q->val)lst=lst->left;
        else break;
    }
    return lst;
}

2016年2月5日 星期五

LEET code -- Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3


return [1,2,3].

反正就是走前序
root, left, right
中序
left,root,right
後續
left,right,root

但是因為不知道有多少資料要被記錄
所以要先知道tree的深度,才知道要先malloc多少記憶體空間
再把資料刷進去

要注意returnSize 這邊是指標  但是他外面應該是(&returnSize)傳進來的
所以直接給他值就好




 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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    int Height = findHeight(root);
    int Size=0;
    int *travel =(int *)malloc(sizeof(int)*pow(2,Height));
    travelorder(root,&Size,travel);
    *returnSize=Size;
    printf("ans:%d,size=%d ",travel[0],*returnSize);
    return travel;
}

int travelorder(struct TreeNode* root, int *Size,int *travel){
    if(root==NULL)return;
    travel[*Size]=root->val;
    printf("size=%d ,value=%d ",*Size,root->val);
    *Size+=1;
    travelorder(root->left,Size,travel);
    
    travelorder(root->right,Size,travel);
    return;
    
}

int findHeight(struct TreeNode* root){
    if(root==NULL)return 0 ;
    int l=findHeight(root->left);
    int r=findHeight(root->right);
    return 1+ (l>=r? l:r);
}
-----

iterative 

必須要寫一個stack來控制


 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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    //int Height = findHeight(root);
    int StackSize=0,TravelSize=0,StackCap=128,TravelCap=128;
    struct TreeNode ** stack=malloc(sizeof(struct TreeNode*)*StackCap);
    int *travel =(int *)malloc(sizeof(int)*TravelCap);
    stack[StackSize++]=root;
    while(StackSize!=0){
        struct TreeNode *temp = stack[--StackSize];
        if (temp!=NULL){
            if(StackSize >=StackCap*0.75 ){
                //increase stack size
                stack=realloc(stack,sizeof(struct TreeNode*)*StackCap*2);
                StackCap*=2;
            }
            if(TravelSize >= TravelCap*0.75){
                travel = realloc(travel,sizeof(int)*TravelCap*2);
                TravelCap*=2;
            }
            travel[TravelSize++]=temp->val;
            stack[StackSize++]=temp->right;//because the left need to be out first
            stack[StackSize++]=temp->left;
            
        }
    }
    *returnSize=TravelSize;
    printf("ans:%d,size=%d ",travel[0],*returnSize);
    return travel;
}

2016年2月4日 星期四

LEET code -- Missing Number

 Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

頗簡單
反正你可以利用 梯形公式把總數算出來


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
int missingNumber(int* nums, int numsSize) {
    if(numsSize==0)return 0;
    int Addtotal=0;
    int Truetotal=((numsSize+1)*numsSize)/2;
    for(int i=0;i<numsSize;i++){
        Addtotal+=nums[i];
    }
    if(Addtotal == Truetotal){
        //miss 0 
        return 0;
    }else{
        return Truetotal-Addtotal;
    }
}
--------------
還有利用XOR來找出答案的


1
2
3
4
5
6
7
8
int missingNumber(int* nums, int numsSize) {
    int i,x=nums[0],y=0;
    for(i=1;i<numsSize;i++)
    x^=nums[i];
    for(i=1;i<=numsSize;i++)
    y^=i;
    return x^y;
}