微軟編程題目

鏈表反轉

單向鏈表的反轉是一個經常被問到的一個面試題,也是一個非常基礎的問題。比如一個鏈表是這樣的: 1->2->3->4->5 通過反轉後成爲5->4->3->2->1。最容易想到的方法遍歷一遍鏈表,利用一個輔助指針,存儲遍歷過程中當前指針指向的下一個元素,然後將當前節點元素的指針反轉後,利用已經存儲的指針往後面繼續遍歷。源代碼如下:

struct linka {

     int data;

     linka* next;

};

 

void reverse(linka*& head)

{

     if(head ==NULL)

          return;

     linka*pre, *cur, *ne;

     pre=head;

     cur=head->next;

     while(cur)

     {

          ne = cur->next;

          cur->next = pre;

          pre = cur;

          cur = ne;

     }

     head->next = NULL;

     head = pre;

}

還有一種利用遞歸的方法。這種方法的基本思想是在反轉當前節點之前先調用遞歸函數反轉後續節點。源代碼如下。不過這個方法有一個缺點,就是在反轉後的最後一個結點會形成一個環,所以必須將函數的返回的節點的next域置爲NULL。因爲要改變head指針,所以我用了引用。算法的源代碼如下:

linka* reverse(linka* p,linka*& head)

{

     if(p == NULL || p->next == NULL)

     {

          head=p;

          return p;

     }

     else

     {

          linka* tmp = reverse(p->next,head);

          tmp->next = p;

          return p;

     }

}

 

判斷兩個數組中是否存在相同的數字

給定兩個排好序的數組,怎樣高效得判斷這兩個數組中存在相同的數字?
這個問題首先想到的是一個O(nlogn)的算法。就是任意挑選一個數組,遍歷這個數組的所有元素,遍歷過程中,在另一個數組中對第一個數組中的每個元素進行binary search。用C++實現代碼如下:

bool findcommon(int a[],int size1,int b[],int size2)

{

     int i;

     for(i=0;i<size1;i++)

     {

          int start=0,end=size2-1,mid;

          while(start<=end)

          {

               mid=(start+end)/2;

               if(a[i]==b[mid])

                    return true;

               else if (a[i]<b[mid])

                    end=mid-1;

               else

                    start=mid+1;

          }

     }

     return false;

}

後來發現有一個 O(n)算法。因爲兩個數組都是排好序的。所以只要一次遍歷就行了。首先設兩個下標,分別初始化爲兩個數組的起始地址,依次向前推進 。推進的規則是比較兩個 數組中的數字,小的那個數組的下標向前推進一步,直到任何一個數組的下標到達數組末尾時,如果這時還沒碰到相同的數字,說明數組中沒有相同的數字。

bool findcommon2(int a[], int size1, int b[], int size2)

{

     int i=0,j=0;

     while(i<size1 && j<size2)

     {

          if(a[i]==b[j])

               return true;

          if(a[i]>b[j])

               j++;

          if(a[i]<b[j])

               i++;

     }

     return false;

}

 

 

最大子序列

問題:
給定一整數序列A1 A2... An (可能有負數),求A1~An的一個子序列Ai~Aj,使得AiAj的和最大
例如:
整數序列-2, 11, -4, 13, -5, 2, -5, -3, 12, -9的最大子序列的和爲21
對於這個問題,最簡單也是最容易想到的那就是窮舉所有子序列的方法。利用三重循環,依次求出所有子序列的和然後取最大的那個。當然算法複雜度會達到O(n^3)。顯然這種方法不是最優的,下面給出一個算法複雜度爲O(n)的線性算法實現,算法的來源於Programming Pearls一書。

在給出線性算法之前,先來看一個對窮舉算法進行優化的算法,它的算法複雜度爲O(n^2)。其實這個算法只是對對窮舉算法稍微做了一些修改:其實子序列的和我們並不需要每次都重新計算一遍。假設Sum(i, j)A[i] ... A[j]的和,那麼Sum(i, j+1) = Sum(i, j) + A[j+1]。利用這一個遞推,我們就可以得到下面這個算法:

int max_sub(int a[],int size)

{

     int i,j,v,max=a[0];

     for(i=0;i<size;i++)

     {

          v=0;

          for(j=i;j<size;j++)

          {

               v=v+a[j];//Sum(i, j+1) = Sum(i, j) + A[j+1]

               if(v>max)

                    max=v;

          }

     }

     return max;

}

那怎樣才能達到線性複雜度呢?這裏運用動態規劃的思想。先看一下源代碼實現:

int max_sub2(int a[], int size)

{

     int i,max=0,temp_sum=0;

     for(i=0;i<size;i++)

     {

          temp_sum+=a[i];

          if(temp_sum>max)

               max=temp_sum;

          else if(temp_sum<0)

               temp_sum=0;

     }

     return max;

}

在這一遍掃描數組當中,從左到右記錄當前子序列的和temp_sum,若這個和不斷增加,那麼最大子序列的和max也不斷增加(不斷更新max)。如果往前掃描中遇到負數,那麼當前子序列的和將會減小。此時temp_sum 將會小於max,當然max也就不更新。如果temp_sum降到0時,說明前面已經掃描的那一段就可以拋棄了,這時將temp_sum置爲0。然後,temp_sum將從後面開始將這個子段進行分析,若有比當前max大的子段,繼續更新max。這樣一趟掃描結果也就出來了。

 

 

找出單向鏈表的中間結點

這道題和解判斷鏈表是否存在環,我用的是非常類似的方法,只不過結束循環的條件和函數返回值不一樣罷了。設置兩個指針p1p2。每次循環p1向前走一步,p2向前走兩步。當p2到達鏈表的末尾時,p1指向的時鏈表的中間。

link* mid(link* head)

{

            link* p1,*p2;

            p1=p2=head;

            if(head==NULL || head->next==NULL)

                        return head;

            do {

                        p1=p1->next;

                        p2=p2->next->next;

            } while(p2 && p2->next);

            return p1;

}

按單詞反轉字符串

並不是簡單的字符串反轉,而是按給定字符串裏的單詞將字符串倒轉過來,就是說字符串裏面的單詞還是保持原來的順序,這裏的每個單詞用空格分開。例如:
Here is www.zhuxinquan.com
經過反轉後變爲:
www.zhuxinquan.com is Here
如果只是簡單的將所有字符串翻轉的話,可以遍歷字符串,將第一個字符和最後一個交換,第二個和倒數第二個交換,依次循環。其實按照單詞反轉的話可以在第一遍遍歷的基礎上,再遍歷一遍字符串,對每一個單詞再反轉一次。這樣每個單詞又恢復了原來的順序。

char* reverse_word(const char* str)

{

     int len = strlen(str);

     char* restr = new char[len+1];

     strcpy(restr,str);

     int i,j;

     for(i=0,j=len-1;i<j;i++,j--)

     {

          char temp=restr[i];

          restr[i]=restr[j];

          restr[j]=temp;

     }

     int k=0;

     while(k<len)

     {

          i=j=k;

          while(restr[j]!=' ' && restr[j]!='/0' )

               j++;

          k=j+1;

          j--;

          for(;i<j;i++,j--)

          {

               char temp=restr[i];

               restr[i]=restr[j];

               restr[j]=temp;

          }

     }

     return restr;

}

如果考慮空間和時間的優化的話,當然可以將上面代碼裏兩個字符串交換部分改爲異或實現。
例如將

 

          char temp=restr[i];

          restr[i]=restr[j];

          restr[j]=temp;


改爲

 

          restr[i]^=restr[j];

          restr[j]^=restr[i];

          restr[i]^=restr[j];

 

 

判斷鏈表是否存在環

問題:判斷一個鏈表是否存在環,例如下面這個鏈表就存在一個環:
例如N1->N2->N3->N4->N5->N2就是一個有環的鏈表,環的開始結點是N5

這裏有一個比較簡單的解法。設置兩個指針p1p2。每次循環p1向前走一步,p2向前走兩步。直到p2碰到NULL指針或者兩個指針相等結束循環。如果兩個指針相等則說明存在環。

struct link {

    int data;

    link* next;

};

 

bool IsLoop(link* head)

{

    link* p1=head, *p2 = head;

            if (head ==NULL || head->next ==NULL) {

                        return false;

            }

    do{

        p1= p1->next;

        p2 = p2->next->next;

    } while(p2 && p2->next && p1!=p2);     

            if(p1 == p2)

                        return true;

            else

                        return false;

}

 

 

刪除數組中重複的數字

問題:一個動態長度可變的數字序列,以數字0爲結束標誌,要求將重複的數字用一個數字代替,例如:
將數組 1,1,1,2,2,2,2,2,7,7,1,5,5,5,0 轉變成1,2,7,1,5,0

問題比較簡單,要注意的是這個數組是動態的。所以避免麻煩我還是用了STLvector

#include <iostream>

#include <vector>

using namespace std;

//remove the duplicated numbers in an intger array, the array was end with 0;

//e.g. 1,1,1,2,2,5,4,4,4,4,1,0 --->1,2,5,4,1,0

void static remove_duplicated(int a[], vector<int>& _st)

{

            _st.push_back(a[0]);

            for(int i=1;_st[_st.size()-1]!=0;i++)

            {

                        if(a[i-1]!=a[i])

                                     _st.push_back(a[i]);

            }

}

當然如果可以改變原來的數組的話,可以不用STL,僅需要指針操作就可以了。下面這個程序將修改原來數組的內容。

void static remove_duplicated2(int a[])

{

            if(a[0]==0 || a==NULL)

                        return;

            int insert=1,current=1;

            while(a[current]!=0)

            {

                        if(a[current]!=a[current-1])

                        {

                                     a[insert]=a[current];

                                     insert++;

                                     current++;

                        }

                        else

                                     current++;

            }

            a[insert]=0;

}

 

 

字符串反轉

我沒有記錯的話是一道MSN的筆試題,網上無意中看到的,拿來做了一下。題目是這樣的,給定一個字符串,一個這個字符串的子串,將第一個字符串反轉,但保留子串的順序不變。例如:
輸入: 第一個字符串: "This is zhuxinquan's Chinese site: http://www.zhuxinquan.com/cn"
子串: "zhuxinquan"
輸出: "nc/moc.zhuxinquan.www//:ptth :etis esenihC s'zhuxinquan si sihT"
一般的方法是先掃描一邊第一個字符串,然後用stack把它反轉,同時記錄下子串出現的位置。然後再掃描一遍把記錄下來的子串再用stack反轉。我用的方法是用一遍掃描數組的方法。掃描中如果發現子串,就將子串倒過來壓入堆棧。
最後再將堆棧裏的字符彈出,這樣子串又恢復了原來的順序。源代碼如下:

#include <iostream>

#include <cassert>

#include <stack>

using namespace std;

//reverse the string 's1' except the substring 'token'.

const char* reverse(const char* s1, const char* token)

{

            assert(s1 && token);

            stack<char> stack1;

            const char* ptoken = token, *head = s1, *rear = s1;

            while (*head != '/0')

            {

                        while(*head!= '/0' && *ptoken == *head)

                        {

                                     ptoken++;

                                     head++;

                        }

                        if(*ptoken == '/0')//contain the token

                        {

                                     const char* p;

                                     for(p=head-1;p>=rear;p--)

                                                 stack1.push(*p);

 

                                     ptoken = token;

                                     rear = head;

                        }

                        else

                        {

                                     stack1.push(*rear);

                                     head=++rear;

                                     ptoken = token;

                        }

            }

            char * return_v = new char[strlen(s1)+1];

            int i=0;

            while(!stack1.empty())

            {

                        return_v[i++] = stack1.top();

                        stack1.pop();

            }

            return_v[i]='/0';

            return return_v;

}

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

{

            

            cout<<"This is zhuxinquan's Chinese site: http://www.zhuxinquan.com/cn/n";

            cout<<reverse("This is zhuxinquan's Chinese site: http://www.zhuxinquan.com/cn","zhuxinquan");

            return 0;

}

 

 

如何判斷一棵二叉樹是否是平衡二叉樹

問題:判斷一個二叉排序樹是否是平衡二叉樹
這裏是二叉排序樹的定義
解決方案:
根據平衡二叉樹的定義,如果任意節點的左右子樹的深度相差不超過1,那這棵樹就是平衡二叉樹。
首先編寫一個計算二叉樹深度的函數,利用遞歸實現。

template<typename T>

static int Depth(BSTreeNode<T>* pbs)

{

            if (pbs==NULL)

                        return 0;

            else

            {

                        int ld = Depth(pbs->left);

                        int rd = Depth(pbs->right);

                        return 1 + (ld >rd ? ld : rd);

            }

}

下面是利用遞歸判斷左右子樹的深度是否相差1來判斷是否是平衡二叉樹的函數:

template<typename T>

static bool isBalance(BSTreeNode<T>* pbs)

{

            if (pbs==NULL) 

                        return true;

            int dis = Depth(pbs->left) - Depth(pbs->right);

            if (dis>1 || dis<-1 )

                        return false;

            else

                        return isBalance(pbs->left) && isBalance(pbs->right);

}

 

strstr()的簡單實現

strstr(s1,s2)是一個經常用的函數,他的作用就是在字符串s1中尋找字符串s2如果找到了就返回指針,否則返回NULL
下面是這個函數的一個簡單實現:

static const char* _strstr(const char* s1, const char* s2)

{

     assert(s2 && s1);

     const char* p=s1, *r=s2;

     while(*p!='/0')

     {

          while(*p++==*r++);

          if(*r=='/0')

               return p;

          else

          {

               r=s2;

               p=++s1;

          }

     }

     return NULL;

}

 

What’s the output?

 

char *GetMemory(void)

{

char p[] = "hello world";

return p;

}

void Test(void)

{

char *str = NULL;

str = GetMemory();

printf(str);

}

 

 

// input = 123456, 1+2+3+4+5+6 = 21, 3

int add(int num){

    int tmpInt = num;

    int sum = 0;

    for(;tmpInt<10;){

       sum += tmpInt%10;

        tmpInt /=10;

    }

    sum += tmpInt;

    return sum;

}

 

int F(int input)

{

    tmp = add(input);

    while(tmp>10){

        tmp = add(tmp);

    }

    return tmp;    

}

 

找到字符串中由相同字符以不同順序組成的單詞

 

Write a function to find all anagrams in the string containing words separated by spaces. The function shall print anagrams on separate lines. So if input is:

"tester spot street stop foo tester"

output shall be:

"tester street tester"

"spot stop"

 

#define MAX = 26

#define MAX_WORD = 100

 

char * G_strParse;

int G_count;

int G_current_Index;

 

int map[MAX_WORD][MAX] ;

 

typedef struct Node{

    int index;

    Node * pNext;

}

 

m

 

char * getNext(){

    char * pWord = null;

    while(G_strParse[count++] == ' ');

    pWord =   G_strParse[G_count];

    if(*pWord != NULL){

        while(G_strParse[G_count++] != ' ' || G_strParse != NULL);

    }

    G_current_Index ++;

    return pWord;

}

 

void deepParse(char * pWord){

    int i;   

    for(i = 0; pWord[i] != NULL; i++){

        map[G_current_Index -1][pWord[i] - 97]++;

    }

}

 

void compareMap(){

    for(int i = 0; i < G_count; i++){

        for(int j = i + 1; j < G_count; j++){

            for(int k=0; k < MAX; k++){

                if(map[i][k] != map[j][k]){

                   

                }

            }

        }

    }   

}

 

void parser(char * strParse){

    char * pWord = NULL;

    G_strParse = strParse;

    G_count = 0;

    G_current_Index = 0;

    while((pWord = getNext() )!= NULL){

        deepParse(pWord);

    } 

    G_count = G_current_Index;

    compareMap();

}

 

int ADD(int a, int b)

1,2

0,0

1,6

10, 5

1000, 956

-1,100

-555, 22200

231次方-1, 231次方-1

231次方-1,-231次方-1

231次方-1,,-231次方-1

231次方-1, 1

 

Fill Table Row(it’s a IQ test question)

Here is a table include the 2 rows. And the cells in the first row have been filled with 0~4. Now you need to fill the cells in the second row with integer. It must to follow the rule.

Rule:

If the first cell in the second row is filled with A, then A mean that the number “0” appears A times in the second row.

Same things is at the other cells, if the second cell is filled with B, then “1” will appear B times in the second row.

0          1          2          3          4

The answer is 2 1 2 0 0

Reverse the words in a string

 

Please write a routine that will take an input string and reverse the words in it.

e.g. abc def -> cba fed

 

->"abc def"

-> "cba fed"

 

typedef struct node

{

      char ch;

      node *next, * perior;

} *String;

 

void clearString(String str)

{

      node *tempNode = NULL;

      if (str == NULL)

           return;

      tempNode = str;

     while(tempNode->next != NULL)

           tempNode->ch='/0';

}

 

void addCharIntoString(String str, char ch) {

      node *tempNode = NULL;

      if ((str == NULL) || (ch == '/0'))

           return;

     

      tempNode = str;

      while(tempNode->next != NULL)

      {

           if (tempNode->ch == '/0')

                 tempNode->ch = ch;

          

      }

}

 

void reverseString(String str)

{

      if (str == NULL)

      {

           printf("the given string is NULL./n");

           return;

      }

     

      node *tempNode = str;

     

      while(tempNode->perior != NULL)

      {

           printf("%c", tempNode->ch);

      }

      printf(" "); 

}

 

void main()

{

      char charList[100];

     printf("Please input the string:");

      scanf("%s", charList);

     

      int i;

      char *temp;

      for(temp = charList; *temp != '/0'; temp++)

      {

           if (*temp == ' ')

                clearString();

           else

                 addCharIntoString();

      }

}

 

[Erbil] Could you please return a char* to the reversed string rather than printing out?

But my string  is a double linkest, how can I supply the char* for the whole string?

 

 

[Erbil] char* ReverseWords(char *);

1. input the NULL string

2. input the Long string, maybe you can get it from a file.

3. input a string don't contain the '/0' character 4. according the above plan to check the output string. Maybe there are some problems occurred in the return string. such as the NULL return string or the order and so on.

5. of course, I will test it in different kind of character system. such as chinese, japanese and so on.

 

Can you give couple of more example tests?

 ok

 

char * result = ReverseWords(NULL);

char * result = ReverseWords(/*MSG0*/"你好");

 

char charList[10]= {'h','e','l','l','o','

','w','o','r','d'};

 

 

------ halw interview starts here ------- give me a minute...

 

can you see this?

y

 

char *strstr( char *subString, char *mainString ) {

 

// example strstr( "abc", "foobarabcdefghij" ) would return "abcdefghij"

 

//KMP method

#define MAX 10

     

void getNextList(char *mode, int*next)

{

     int i = 0; int j = 0;

      next[i] = i; next[j] = j;

 

      int length = strlen(mode);

      while(j<length)

      {

           if (mode[i] == mode[j])

           {i++;j++;next[j]=i+1;}

           else

           {

                 if(i == 0)

                 {j++;next[j]= i+1;}

                 else

                 i = next[i] -1;

           }

      }        

}

 

char *strstr( char *subString, char *mainString ) {

     int next[MAX];

      int i,j;

 

      getNextList(subString, next);

     

      int subLength = strlen(subString);

      int mainLength = strlen(mainString);

     

      if( ((subLength)>(mainLength +1)) || (subLength ==

0))

           return NULL;

 

      i = 0; j = 0;

      while((i<mainLength) && (j<subLength))

      {

           if (mainString[i] == subString[j])

           {i++; j++;}

           else

                 if (j == 0)

                      i++;

                 else

                      j = next[j-1];  

      }

 

      return (mainString +i -j);

}

 

test cases

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

 

 

substring               mainstring

==========      ===========

1.NULL            not NULL

2.not NULL       NULL

3.NULL            NULL

4.abcd             abcdefg

5.abc               123abc

6.aaaaabc        abc

7.aaabbbbcccccc          1234aaabbbcccccc4536

 

what about

 

abcdefg                 abc

abc            xyzab

 

 

1. Do you know what Binary Search is?

 

 

 

2. Find the k smallest elements in an array

 

Example:

array = { 4, 13, 2, 17, 9, 11, 6 }

k = 3

 

Result = { 2, 4, 6 }

i see quesion

 

Can you write the signature of the method?

What language are you using? JAVA

 

TheSmallest( ArrayList  a, int k)

{

if(

 

 ArrayList   smallest;;

 

int max ;//this value is max in smallest

int temp;

for(int i =0;i<=a.len;i++)    

{

            // con

           

            temp = a(i);      

             if( temp < max ))                                    <---- what is max?

                       {

                       //nsert a value to smallest

                        for(int j=0;j<=k;j++)                               

                       {

                           if(temp <smallest(j))                <--- What happens when i < k

                         {

                                     int inerTemp =smallest(j);         

                                     smallest(j) =small;

                         // move the lest values

                                     for(int n=j+1;n<k;n++)                <--- Do you need this loop?

                                    {

                           smallest(n)=inerTemp ;

                            inerTemp =smallest(n);                                                                             

                                    }

                        max = smallest(k);

                       }

                       }

                                                            <--- You need to return a value here

}

 

 

****** Can you write some test cases for the code above

yes

 do you mean I make test cases first?

 

i mean give me some input cases that you think will be interesting for the code

 

For example:

 

1. array = null

2. k = -10

 

 

 

 

            insert a value to smallest,

            find a value

            no ,there i have not finished

             i want constuct a list of the smallest,the defaut value is  the Max Interger

            [Arun] Do you want to use the first k elements in the array instead?

            [liu] yes

            constuct

            yes

 

 

array = { 4, 13, 2, 17, 9, 11, 6 }

Can you walk me through your code using the array above

 

 

do you mean can i build a tree

Can you trace the algoritm using the array below

what mean of trace?

yes

.i see

 

k = 3

 

array = { 4, 13, 2, 17, 9, 11, 6 }

smallest={2,`4,13}

max = 17

 

array = { 4, 13, 2, 17, 9, 11, 6 }

smallest={2,`4,9}

max = 9

 

array = { 4, 13, 2, 17, 9, 11, 6 }

smallest={2,`4,6}

max = 6

 

 

Find the maximum value of a contiguous subsequence

 

Given a integer (possible nagative) A1, A2, ..., An. Find the maximum value of a contiguous subsequence. If all integers are negative, the sum is 0.

 

2 -5 2 3 4 -20 7

 

2 + 3 + 4 = 9

 

5 6 -3 4 6 7

 

 

Max(List input)

{

            List results;

            List tempResults;

            int temsum =0;

            int sum =0;       

            for (int i =0;i<input.Len)

                        {

                                 if (sum > temsum +input(i))

                                       {

                                    tempResults = null;

                                    temsum =0;                              

                                       }

                                 if(input(i)>0)

                                                 {

                                    tempResults.add(input(i));

                                    temsum = temsum +input(i);

                                                  }

                                  else

                                                 {

                                    results= tempResults;                           

                                    sum = temsum ;

                                    tempResults.add(input(i));

                                    temsum = temsum +input(i);                              

                                                  }                                

                        }

            if(sum>temsum)

            {

                  return results;

            }else

            {

                  return tempResults;

            }

}

 

2 -5 2 3 4 -20 7

 

tempResults={2}

results={2}

tempsum=2

sum=2

 

tempResults={2,-3}

results={2}

tempsum = -3

sum=2

 

tempResults={2}

tempsum = 2

results={2}

sum=2

 

tempResults={2,3}

tempsum = 5

results={2}

sum=2

 

tempResults={2,3,4}

tempsum=9

results={2}

sum=2

 

tempResults={2,3,4,-20}

tempsum=-11

results={2,3,4}

sum=9

 

tempResults={7}

tempsum=7

results={2,3,4}

sum=9

 

 

2 -5 2 3 4 -2 7

 

tempResults={2}

rtempsum=2

results={}

sum=

 

tempResults={2,-5}

tempsum=-3

results={2}

sum=2

 

tempResults={2}

tempsum =2

results={2}

sum=2

 

tempResults={2,3}

tempsum=5

results={2}

sum=2

 

tempResults={2,3,4}

tempsum=9

results={2}

sum=2

 

tempResults={2,3,4,-2}

tempsum=7

results={2,3,4}

sum=9

 

tempResults={2,3,4,-2,7}

tempsum=14

results={2,3,4}

sum=9

 

(for java)

Could you please explain the use of the override and abstract concepts for methods?

 

Override mean the sub classs can have the same name method with the super class , but can do its own something.

which may be not  the same with the super class.

 

abstract meats that  the class must have a sub class ,  You can  not new  a instance with it .

 

 

public class A

{

   public static int add( int a, int b);

}

 

public class B

{

   public void foo()

  {

       int a = 1;

       int b =2 ;

       int c = A.add(a, b) ;           //that is  static method    

      //

  }

}

 

Fibonacci sequence of numbers: 1 1 2 3 5 8 13...

 

public int Fib(int n)  {

            return Fib(n-1) + Fib(n-2);         //wrong

 

                 if(n ==1){

            return  n;                           

               } else if(n ==2){

            return n-1;

               } else{

            return rerurn Fib(n-1) + Fib(n-2);

              }                                

}

 

Fib(0) =  undefined

Fib(1) = 1

Fib(2) = 1

Fib(3) = 2...

 

assume n > 0

 

   

 Binary Search Tree

Find the nearest common ancestor of any two nodes in a binary search tree

 

           10

        /        /

      6          15

     / /           /  /

   3    8     12   18

  /     / /

 1    7   9

            /

          8.5

 

Example: the nearest common ancestor of 1 and 7 is 6

 

class TreeNode {

   TreeNode Left;

   TreeNode Right;

   TreeNode Parent;

    int Data;

}

 

 

Find ancestor of 1 and 8.5 using your approach

first  i will find  1, 3, 6, 10

then I will find    8.5 , 9, 8, 6, 10

thirdly,  i compare the tow sequence and find the fist  same one.    that is 6

 

Can you give the algorithm for comparing the sequence

 

      TreeNode  Find(TreeNode

 

     1 compare  (8.5 , 9, 8, 6, 10 )

     3 compare ()

 

Thanks... I got you answer. Now can you write code for FindAncestor below:

 

 

 

TreeNode FindAncestor( TreeNode node1, TreeNode node2){

 

     TreeNode node1p[] = new TreeNode[100]  ;     <----- What if my tree has height 200?

    TreeNode node2p[]  = null;

    node1p[0] =  node1;               <---- Null Reference Exception

    node2p[0] =  node2 ;              <---- whats wrong here?

 

    int i =1;

    while(node1.Parent  != null){

          node1 = node1.Parent;

          node1p[i++] =  node1 ;       

    }

 

   int j =1;

    while(node2.Parent  != null){

          node2 = node2.Parent;                                <------------ Do you need this loop?

          node2p[j] =  node2 ;

    }

    

    for(int n =0; n<= node1p . size(); n++)              

   {

          for(int m =0; m< node2p . size(); m++)

          {

            if(node1p[n] != node2p[m] ){

                        contine;

            }else{

                        return node1p[n];

            }

         }

  }

           

}

 

 

 Can you give me the approach first before you write code?

 

 

Implement code for Binary Search

 

( 3, 6, 10, 14, 18, 20, 25 )

  |    |     |

 0   1    2

 

Search( 10 ) will return 2... which is the index of the 10 in the array

 

 

int  Search( int[] array, int point1, int point2, int valueToSearch )

{

       

         int point =  array .length()/2;

         int point1 = 0;

         int poin2 = array.length();

 

 

        if(valueToSearch  ==array[point] ) {

            return point;

        }else if(valueToSearch < array[point]) {                          

              point2 = point;                                  

              search (array, point1, point2,  valueToSearch )                         

        }else {

              point1 = point;                                               

              search (array, point1, point2,  valueToSearch )               

      }

        

       return -1;                                       // not find the element.                

}

 

 Can you give me one test case for this?

 

 

   int []arrayA ={ 3, 6, 10, 14, 18, 20, 25 }

   search(arrayA,  0,  arrayA.length,  10);

 

實現一個大數的階層,比如1000的階層

void foo(int v)

val = multi(v);

bitmulti

moveleft

add

 

單鏈表找倒數第N個節點(橡皮筋算法)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章