有兩數組A、B,長度分別為m、n。用不超過m+n的比較次數找到兩個數組中的相同元素

來源:互聯網
上載者:User

標籤: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。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.