標籤:style blog color os cti for
今天碰到一道筆試題:有兩數組A、B,長度分別為m、n。用不超過m+n的比較次數找到兩個數組中的相同元素。當時沒做出來,我現在給出C#版本,算是彌補一點遺憾。
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SortAB{ class Program { static void Main(string[] args) { int[] A = RandomIntArray(10); // m = 10 int[] B = RandomIntArray(5); // n = 5 // 輸出兩個數組 Console.Write("數組A:"); foreach(int m in A) Console.Write("{0} ", m.ToString()); Console.Write("\n數組B:"); foreach (int n in B) Console.Write("{0} ", n.ToString()); // 找出數組中相同的元素 StringBuilder list = new StringBuilder(); foreach (int m in A) { int getInt = find(m, B); if (getInt != -1) list.Append(B[getInt]); } Console.WriteLine(); Console.Write("兩個數組中重複的元素有:{0} ", list); // 用兩個數組的交集,來驗證 IEnumerable<int> intersect = A.Intersect(B); Console.Write("\n兩個數組的交集:"); foreach (int vars in intersect) Console.Write("{0} ", vars); Console.ReadLine(); } // 二分尋找。N 必須為有序數組,否則會出錯 public static int find(int key, int[] N) { int lb = 0; int ub = N.Length - 1; int temp; while(true) { temp = (lb + ub)/2; if(N[temp] == key) return temp; else if(lb > ub) return -1; else { if(N[temp] < key) lb = temp+1; else ub = temp-1; } } } public static int[] RandomIntArray(int count) { int[] array = new int[count]; Random r = new Random(unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < count; i++) { array[i] = r.Next(100); } return array; } } }
不過,我現在仍是疑惑:比較次數有可能會大於m+n。