C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法
本文實(shí)例講述了C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法。分享給大家供大家參考。具體如下:
1.算法描述
0)輸入合法性校驗(yàn)
1)建立臨時(shí)數(shù)組:與原數(shù)組元素一樣。該步驟的目的是防止傳入的原數(shù)組被破壞
2)對(duì)臨時(shí)數(shù)組進(jìn)行排序
3)統(tǒng)計(jì)臨時(shí)數(shù)組共有多少個(gè)不同的數(shù)字。該步驟的目的是為了確定結(jié)果集數(shù)組的長度
4)建立結(jié)果集數(shù)組,只存放不同的數(shù)字
5)返回結(jié)果集
2.函數(shù)代碼
/// <summary> /// 建立包含原數(shù)組內(nèi)所有元素且元素間互不重復(fù)的新數(shù)組 /// </summary> /// <param name="array">原數(shù)組</param> /// <param name="isAsc">true:升序排列/false:降序排列</param> /// <returns>新數(shù)組</returns> private static int[] DifferentElements(int[] array, bool isAsc = true) { //0.輸入合法性校驗(yàn) if (array == null || array.Length == 0) { return new int[] { }; } //1.臨時(shí)數(shù)組:與原數(shù)組元素一樣 int[] tempArray = new int[array.Length]; for (int i = 0; i < tempArray.Length; i++) { tempArray[i] = array[i]; } //2.對(duì)臨時(shí)數(shù)組進(jìn)行排序 int temp; for (int i = 0; i < tempArray.Length; i++) { for (int j = i; j < tempArray.Length; j++) { if (isAsc) { if (tempArray[i] > tempArray[j]) { temp = tempArray[i]; tempArray[i] = tempArray[j]; tempArray[j] = temp; } } else { if (tempArray[i] < tempArray[j]) { temp = tempArray[i]; tempArray[i] = tempArray[j]; tempArray[j] = temp; } } } } //3.統(tǒng)計(jì)臨時(shí)數(shù)組共有多少個(gè)不同的數(shù)字 int counter = 1; for (int i = 1; i < tempArray.Length; i++) { if (tempArray[i] != tempArray[i - 1]) { counter++; } } //4.建立結(jié)果集數(shù)組 int[] result = new int[counter]; int count = 0; result[count] = tempArray[0]; for (int i = 1; i < tempArray.Length; i++) { if (tempArray[i] != tempArray[i - 1]) { count++; result[count] = tempArray[i]; } } //5.返回結(jié)果集 return result; }
3.Main函數(shù)調(diào)用
static void Main(string[] args) { int[] array = new int[] { 1, 9, 1, 9, 7, 2, 2, 5, 3, 4, 5, 6, 3, 3, 6, 2, 6, 7, 8, 0 }; //數(shù)組:包含原數(shù)組內(nèi)全部元素且不重復(fù)(升序排列) int[] result1 = DifferentElements(array); foreach (int i in result1) { Console.Write(i.ToString() + "\t"); } //數(shù)組:包含原數(shù)組內(nèi)全部元素且不重復(fù)(降序排列) int[] result2 = DifferentElements(array,false); foreach (int i in result2) { Console.Write(i.ToString() + "\t"); } Console.ReadLine(); }
4.程序輸出示例
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
c#異步讀取數(shù)據(jù)庫與異步更新ui的代碼實(shí)現(xiàn)
這篇文章主要介紹了c#從數(shù)據(jù)庫里取得數(shù)據(jù)并異步更新ui的方法,大家參考使用吧2013-12-12WPF如何利用附加屬性修改ShowGridLines效果詳解
這篇文章主要給大家介紹了關(guān)于WPF如何利用附加屬性修改ShowGridLines效果的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2018-04-04C#值類型、引用類型中的Equals和==的區(qū)別淺析
這篇文章主要介紹了C#值類型、引用類型中的Equals和==的區(qū)別淺析,本文分別對(duì)C#值類型和引用類型中的Equals和==做了講解和給出了實(shí)例,需要的朋友可以參考下2015-01-01C#中ListView控件實(shí)現(xiàn)窗體代碼
這篇文章主要介紹了C#中ListView控件實(shí)現(xiàn)窗體的核心代碼,非常不錯(cuò),具有參考借鑒價(jià)值,對(duì)c#listview相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2016-08-08