zoukankan      html  css  js  c++  java
  • 一个随机排序集合的思考

    我是让已知一个数组的元素随机排列,我开始到网上搜搜,代码如下:

            private static List<string>  RaD(List<string> strTemp)
            {
                List<string> newList = new List<string>();
                Random r = new Random();
                while (true)
                {
                    int i = r.Next(0, strTemp.Count);
                    if (!newList.Contains(strTemp[i]))
                        newList.Add(strTemp[i]);
                    if (newList.Count == strTemp.Count)
                        break;
                }
                return newList;
            }

    大多数都是使用Contains看是否包含,不包含在新集合才添加,但是个人感觉每次都检索一下新数组里面有木有插入元素,这样遍历新数组岂不是很多次,于是我修改了下,我的思路是随机生成一个数,将其添加新数组,然后删除这个数,在添加,代码如下:

        private static List<string> RaD2(List<string> strTemp)
            {
                List<string> newList = new List<string>();
                Random random = new Random();
    
                for (int i = 0; i < strTemp.Count;)
                {
                    int r = random.Next(0, strTemp.Count);
                    newList.Add(strTemp[r]);
                    strTemp.RemoveAt(r);
                }
                return newList;
            }

    个人感觉这样的效率更好,减少了遍历次数,增加的是每次删除元素的操作。以上是个人理解,不知道有木有什么更快的效率更好的方法随机排序集合??欢迎大家拍砖!!

  • 相关阅读:
    重置csr
    修改node节点名称
    k8s报错解决
    k8s测试容器之间是否互通
    MyEclipse------executeBatch()使用方法
    MyEclipse------execute()使用方法
    MyEclipse------如何查询MySQL数据库里面表的信息
    MyEclipse------如何连接MySQL
    MyEclipse------从服务器下载文件
    MyEclipse------各种问题解决方法
  • 原文地址:https://www.cnblogs.com/Yukang1989/p/2748568.html
Copyright © 2011-2022 走看看