微策略筆試試題

1 。奇數個整數,其中只有一個整數重複奇數次,其他的重複偶數次。找出奇數次的整數

肯定是要求了時間複雜度了的,如果按照普通的算法,時間複雜度爲 n^2 ;

異或運算 可以用來進行數據交換:

 

交換兩個數字的大小

  a=9;

  b=10;

  a=a^b;

  b=b^a;

  a=a^b;

  結果是a爲10,b爲9.

 

採用位運算的方法,利用異或運算,兩個相同的數字異或運算爲 0 ,三個相同的數字異或運算爲這個數字。

異或的特性...a^a^b=b

根據這個原理可以

對這個數組進行一次整體的異或運算,最後得到的數字即爲出現奇數次的那個數字。

而且時間複雜度爲 n;

 

int findx(int a[] ,int len)
{
 int m=0;
 int i=0;
    for(i = 0 ;i<len ;i++)
 {
  m = m^(a[i]);
 }
 return m;
}
 void main()
 {
  int a[]={3,2,4,2,4,2,3};
  int m ;
  m = findx(a ,7);
  cout<<m;
 }

2 給出倆個字符串 分別長度爲 m,n str1=""; str2=""; 找出相同的字符,要求時間複雜度小於m*n;

如果不要求時間複雜度那麼採用分別遍歷這兩個字符串即可,但是時間複雜度爲 m*n;

我們利用ASCII碼對應的ASCII碼錶的唯一性,將字符轉換成數字。

例如 字符 a 對應 97 , b 對應與 98 

字符一共有128個,設數組c[128]={0};

設c[97] = 1 表示字符a是存在的,如果=0則表示不存在。

  下面的方法的時間複雜度爲 m+n;

void findx(char *str1 ,char *str2)
{  
 char *p,*s;
 p = str1;
 s = str2;
 int exist[128]={0};
 while(*p != '\0')
 {
  exist[*p] =1;
  p++;
 }
 while(*s != '\0')
 {
  if(exist[*s] == 1)
  {
   printf("%c",*s);
   exist[*s] = 0;
  }
  s++;
 }
}

void main()
{
 char str1[]="abcdef";
 char str2[]="dgmnfig";
 findx(str1 ,str2);
}

3 雙向鏈表的插入,考慮表頭,表尾,以及中間的情況,

這個問題關鍵是這個雙鏈表之前應該是已經排好序了。否則怎會知道插入到什麼位置呢,暫且令鏈表爲升序排列。

 

typedef struct DoubleLinkNode
{
 int data;
 struct DoubleLinkNode *next ,*pre;
}node;
node *create(int n)     //創建雙向鏈表
{
 int x;
 node *head = (node*)malloc(sizeof(node));
 node *p = head;
 node *s;
 while(n)
 {
       s = (node*)malloc(sizeof(node));
    printf("請輸入數據:");
    scanf("%d",&x);
    s->data = x;
    p->next = s;
    s->pre = p ;
    p = s;
    n--;
 }
 s->next = NULL;
 return head;
}
node *insert(node *head ,int a)   //插入鏈表
{
 node *p = (node*)malloc(sizeof(node));
 p->data = a;
 node *s = head->next;
 node *m;
 while((a>s->data)&&(s!=NULL))
 {  
  m  = s;
  s = s->next;
 }
 if(s == head->next)  //表頭
 {
  p->next = s;
  s->pre = p;
  head->next = p;
  p->pre = head;
 }
 else if(s==NULL)  //表尾
 {
  m->next = p;
  p->pre = m;
  p->next = NULL;
 }
 else                   //表中間
 {
  p->next = s;
  s->pre = p;
  m->next = p;
  p->pre = m;
 }
 return head;
}

void display(node *head)  //輸出鏈表
{
 node *p;
 p = head->next;
 while(p != NULL)
 {
  printf("%d",p->data);
  p = p->next;
 }
 printf("\n");
}

void main()
{
 int n;
 printf("請輸入個數:");
 scanf("%d",&n);
 node *head;
 head = create(n);
 display(head);
    node *phead;
 phead = insert(head,4);
 display(phead);
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發佈了93 篇原創文章 · 獲贊 7 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章