首页 > 代码库 > 合并重叠时间段的算法

合并重叠时间段的算法

合并重叠时间段的算法

一.采用非排序:

方案一:

1.文件:Extract_Chao.cs(核心)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Extract
{
    public class Extract_Chao
    {
        List<ExtractInfo> extractList = new List<ExtractInfo>();
        public void Main()
        {
            var list = AddExtract();
            BuidExtract(list, 0);

            for (int i = 0; i < extractList.Count; i++)
            {
                if (extractList[i] == null) continue;
                Console.WriteLine(extractList[i].StartPoint + "-------" + extractList[i].EndPoint);
            }
        }

        private void BuidExtract(List<ExtractInfo> list, int num)
        {
            for (int i = 0; i < list.Count; i++)
            {
          if(i==num)continue;
if (list[i] != null &&list[num]!=null) { if (list[i].StartPoint > list[num].StartPoint && list[i].StartPoint <= list[num].EndPoint) { if (list[i].EndPoint > list[num].EndPoint) { var extractTemp = new ExtractInfo() { StartPoint = list[num].StartPoint, EndPoint = list[i].EndPoint }; list[num] = extractTemp; } list[i] = null; } else if (list[i].EndPoint > list[num].StartPoint && list[i].EndPoint < list[num].EndPoint) { if (list[i].StartPoint < list[num].StartPoint) { var extractTemp = new ExtractInfo() { StartPoint = list[i].StartPoint, EndPoint = list[num].EndPoint }; list[num] = extractTemp; } list[i] = null; } } } num++; if (num < list.Count) { BuidExtract(list, num); } else { extractList = list; } } private List<ExtractInfo> AddExtract() { var list = new List<ExtractInfo>(); list.Add(new ExtractInfo() { StartPoint = 24, EndPoint = 41 }); list.Add(new ExtractInfo() { StartPoint = 58, EndPoint = 75 }); list.Add(new ExtractInfo() { StartPoint = 62, EndPoint = 80 }); list.Add(new ExtractInfo() { StartPoint = 79, EndPoint = 89 }); list.Add(new ExtractInfo() { StartPoint = 5, EndPoint = 10 }); list.Add(new ExtractInfo() { StartPoint = 20, EndPoint = 30 }); list.Add(new ExtractInfo() { StartPoint = 6, EndPoint = 25 }); return list; } } }

 

2. 文件:ExtractInfo.cs(实体)

  public class ExtractInfo
    {
        public double StartPoint { get; set; }

        public double EndPoint { get; set; }
    }

 

3.文件:Program.cs(入口)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Extract
{
    class Program
    {
        static void Main(string[] args)
        {
          
            Extract_Chao chao = new Extract_Chao();
            chao.Main();

            Console.WriteLine("OK");
            Console.Read();
        }
    }
}

 

4.运行结果:

技术分享

二.采用排序算法:

http://www.cnblogs.com/artwl/archive/2011/03/01/1968044.html

 

此算法甚好的,只是不满足我的需求:(上一个终点等于下一个起点的时候)【根据自己的需求选择方案】

例如如下两段时间段:

5-10

10-20

我的需求结果是要合并:5-20

 

 

思路决定程序出路

    ---逻辑与思维


欢迎大家分享更好的算法,独乐不如众乐!                                  

 

 

合并重叠时间段的算法