面試題之演算法面試題(一)
阿新 • • 發佈:2018-11-26
問題:
1. 輸入一個個數較大的正整數陣列[數字範圍在0~9999],將部分陣列元素的十進位制表示連線起來排成一個數,輸出能排出的所有數字中最大的一個。find例如輸入陣列{3423,33,456,9,8,7,21}和3,則輸出的最大數為:456342333。
要求:
(1) 輸出數字用十進位制字串表示
(2)除列印函式和記憶體建立/銷燬函式外,不得使用其它庫函式,如需要相似功能,請自己實現;
解題思路:
首先根據需要取出的元素個數得到陣列中最大的n元素,將其轉化成字串存放到字串陣列中,然後將字串陣列中的元素的第一個字元進行比較,將大的放到前面,如果相等就比較第二個,以此類推(最多比較四次,如果都相等,則兩個元素就完全相等也沒有必要再去交換一次了)。排好序後將其連線就可以了。
程式碼:
class Program { static void Main(string[] args) { int[] array = { 3423, 33, 456, 9, 8, 7, 21 }; Console.WriteLine(largestNumber(array, 3)); } static String largestNumber(int[] array, int numbers) { string result = ""; String[] sum = new String[numbers]; if (numbers >= 1 && numbers <= array.Length) { for (int i = 0; i < numbers; i++) { for (int j = i; j < array.Length - 1; j++) { if (array[j] <= array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } sum[i] = array[i].ToString(); } result = Count(sum); } return result; } static String Count(string[] sum) { string result = ""; for (int i = 0; i < sum.Length; i++) { for (int j = i; j < sum.Length - 1; j++) { if (!Cycle(sum[j], sum[j + 1])) { String temp = sum[j]; sum[j] = sum[j + 1]; sum[j + 1] = temp; } } result += sum[i]; } return result; } //迴圈比較字串陣列中元素的大小 static bool Cycle(string a, string b) { for (int i = 0; i < 4; i++) { if (a[i] > b[i]) { return true; } else if (a[i] == b[i]) { if (i == 3) { return true; } continue; } else { return false; } } return true; } }
當然上面的解題演算法沒有使用到任何的庫函式,下面是使用了庫函式的一種解法。
程式碼:
int[] arr = { 3423, 33, 456, 9, 8, 7, 21 }; int n = 3; var result = arr.OrderByDescending(x => x.ToString().Length) //取最長的 .Take(n) //n個 .OrderByDescending(x => x.ToString());//按字串排序 Console.WriteLine(string.Join("", result));//拼接