微软编程题目

链表反转

单向链表的反转是一个经常被问到的一个面试题,也是一个非常基础的问题。比如一个链表是这样的: 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个节点(橡皮筋算法)

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