zoukankan      html  css  js  c++  java
  • 高效率随机删除数据(不重复)

    算法的复杂度就降低为 O(n) ,速度大大提高。

    需求:前后数据x条不动,中间随机删除N条记录

    高效率随机删除数据 不重复

    实现:

     Dictionary<string, int> dictA = GetArrayListFromTxt(this.txtFileNameA.Text);
    Dictionary<string, int> dictB = GetArrayListFromTxt(this.txtFileNameB.Text);
    Dictionary<string, int> dictC= new Dictionary<string,int>();
    StringBuilder sb=new StringBuilder();
    foreach (var item in dictB)
    {
    if (dictA.ContainsKey(item.Key))
    {
    dictA.Remove(item.Key);
    dictC.Add(item.Key, item.Value);
    sb.AppendLine(item.Key);
    }
    }
    textBox1.Text = sb.ToString();
    txtRepeatNum.Text = Convert.ToString(dictC.Count );
    foreach (object key in RandomValues(dictA,x).Take(n))
    {
    dictA.Remove(key.ToString());
    }

    算法:

     public static IEnumerable<TKey> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict,int num)
    {
    List<TKey> list = Enumerable.ToList( dict.Select(k=>k.Key).Skip(Convert.ToInt32(num)).Take(dict.Count - num * 2));
    Random rand = new Random();
    while (list.Count > 0)
    {
    var point = rand.Next(0, list.Count);
    var rv = list[point];
    list[point] = list[list.Count - 1];
    list.RemoveAt(list.Count - 1);
    yield return rv;
    }
    }
  • 相关阅读:
    request.getParameter() 、 request.getInputStream()和request.getReader() 使用体会
    HTTP之Content-Length
    关于spring3中No Session found for current thread!and Transaction的配置和管理(转)
    Java数据类型和MySql数据类型对应一览
    Spring MVC 解读——View,ViewResolver(转)
    LeetCode 441. Arranging Coins
    LeetCode 415. Add Strings
    LeetCode 400. Nth Digit
    LeetCode 367. Valid Perfect Square
    LeetCode 326. Power of Three
  • 原文地址:https://www.cnblogs.com/zengxiangzhan/p/2229585.html
Copyright © 2011-2022 走看看