打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#不重复输出一个数组中所有元素的方法
/// <summary>
/// 建立包含原数组内所有元素且元素间互不重复的新数组
/// </summary>
/// <param name="array">原数组</param>
/// <param name="isAsc">true:升序排列/false:降序排列</param>
/// <returns>新数组</returns>
private static int[] DifferentElements(int[] array, bool isAsc = true)
{
 //0.输入合法性校验
 if (array == null || array.Length == 0)
 {
  return new int[] { };
 }
 //1.临时数组:与原数组元素一样
 int[] tempArray = new int[array.Length];
 for (int i = 0; i < tempArray.Length; i++)
 {
  tempArray[i] = array[i];
 }
 //2.对临时数组进行排序
 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.统计临时数组共有多少个不同的数字
 int counter = 1;
 for (int i = 1; i < tempArray.Length; i++)
 {
  if (tempArray[i] != tempArray[i - 1])
  {
   counter++;
  }
 }
 //4.建立结果集数组
 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.返回结果集
 return result;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
java常用的7大排序算法汇总
【转】Java工具类
十大经典排序算法(上)
算法系列15天速成
算法设计与分析 2.7 归并排序
LeetCode之Rotate Array
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服