namespace TestApp { using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { , , , , }; for (int i = 0; i < source.Length; i++) { for (int j = i; j < source.Length; j++) { ).Value) > Convert.ToInt32(Regex.Match(source[j], ).Value)) { string temp = source[i]; source[i] = source[j]; source[j] = temp; } } } for (int i = 0; i < source.Length; i++) { Console.WriteLine(source[i]); } } } }
这一题我选择的是用比较笨的正则取出数字,然后用冒泡排序完成的算法。后来回来想了想,实在是不应该啊!这里就上一张传统的冒泡排序视觉效果图。
namespace TestApp { using System; class Program { static void Main(string[] args) { , , , , , , , , , }; foreach (var item in ArrDistinct(source)) { Console.WriteLine(item); } } public static String[] ArrDistinct(string[] source) { if (source != null && source.Length > 0) { Array.Sort(source); int size = 1; for (int i = 1; i < source.Length; i++) if (source[i] != source[i - 1]) size++; string[] tempArr = new string[size]; int j = 0; tempArr[j++] = source[0]; for (int i = 1; i < source.Length; i++) if (source[i] != source[i - 1]) tempArr[j++] = source[i]; return tempArr; } return source; } } }
//因为这题的主要考点在字符串数组去重,所以排序我就没太在意,直接用的系统排序。当然,这样是很不专业的。不过如果有必要的话,这里也可以先用算法排序字符串,然后再用我这个办法。 至于算法排序字符串,我能想到的比较"卑鄙"的办法就只有先将字符串数组转成char再转成int数组, Array.ConvertAll<string, int>(strArray, s => int.Parse(s)); //再排序,大神你有更好的办法?有就不要藏着掖着了,来吧!
第四题public int[] IntArrSort(int[] source) { if (source == null || source.Length == 0) return source; int rightIndex = source.Length - 1, tempNumber = 0; for (int i = 0; i < source.Length; i++) { if (i > rightIndex) break; if (source[i] <= 0) { continue; } else if (source[i] > 0) { for (int j = rightIndex; j >= 0; j--) { if (source[j] < 0) { tempNumber = source[j]; source[j] = source[i]; source[i] = tempNumber; rightIndex = j; break; } } } } return source; }
各位道友,以上所有的算法面试题都是我平常在面试中积累下来的,出场率比较高的我都列出来了(出场率只是相对我面试的经历而言)。