C筆試題之編程題三
阿新 • • 發佈:2019-05-12
另一個 時間 dash fast == 遍歷 nod true 單鏈表
9、寫一個函數找出一個整數數組中第二大的數。—— Microsoft
1 const int MINNUMBER = -32768;//假設int占2個字節 2 3 int find_sec_max(int data[], int count) 4 { 5 int maxnumber = data[0]; 6 int sec_max = MINNUMBER; 7 8 for (int i = 1; i < count; i++) 9 { 10 if (data[i] > maxnumber)11 { 12 sec_max = maxnumber; 13 maxnumber = data[i]; 14 } 15 else 16 { 17 if (data[i] > sec_max) 18 sec_max = data[i]; 19 } 20 } 21 22 return sec_max; 23 }
10、如何判斷一個單鏈表是有環的?不能用標誌位,最多只能用兩個額外指針。
思路:如果一個單鏈表中有環,用一個指針去遍歷,永遠不會結束,所以可以用兩個指針,一個指針一次走一步,另一個指針一次走兩步,如果存在環,則這兩個指針會在環內相遇,時間復雜度為O(n)。
1 struct Node 2 { 3 int data; 4 Node * next; 5 }; 6 typedef struct Node Node; 7 8 bool check(Node * pHead) 9 { 10 if (pHead == NULL) 11 return false; 12 Node * pSlow = pHead;13 Node * pFast = pHead; 14 15 while ((pFast != NULL) && (pFast->next != NULL)) 16 { 17 pSlow = pSlow->next; 18 pFast = pFast->next->next; 19 if (pSlow == pFast) 20 return true; 21 } 22 return false; 23 }
C筆試題之編程題三