110,538
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
// your code goes here
List<int> list1 = new List<int>(){1,2,3,4,5,7,8};
List<int> list2 = new List<int>(){1,4,5,6,7};
List<int> list3 = list1.Union(list2).OrderBy(x => x).Select(x => list1.Any(y => x == y) ? x : 0).ToList();
list2 = list1.Union(list2).OrderBy(x => x).Select(x => list2.Any(y => x == y) ? x : 0).ToList();
list1 = list3;
Console.WriteLine(string.Join(",", list1.Select(x => x.ToString())));
Console.WriteLine(string.Join(",", list2.Select(x => x.ToString())));
}
}
1,2,3,4,5,0,7,8
1,0,0,4,5,6,7,0var list1 = new List<int>()
{
1,2,3,4,5,7,8
};
var list2 = new List<int>()
{
1,3,4,5,6,7
};
var union = list1.Union(list2).OrderBy(i=>i).ToArray();
for(var i=0;i<union.Length;i++)
{
if (i < list1.Count && list1[i] != union[i])
{
list1.Insert(i, 0);
}
if(i>= list1.Count)
{
list1.Add(0);
}
if (i < list2.Count && list2[i] != union[i])
{
list2.Insert(i, 0);
}
if (i >= list2.Count)
{
list2.Add(0);
}
}
首先你的原数据都必须是排序过的 不排序这题没意义
取并集 循环并集 不同的插入0不足的补上0
static void Main(string[] args)
{
List<int> list1 = new List<int> { 1, 2, 3, 4, 5, 7, 8 };
List<int> list2 = new List<int> { 1, 4, 5, 6, 7 };
int min = Math.Min(list1.Min(), list2.Min());
int max = Math.Max(list1.Max(), list2.Max());
// 方法1
List<int> list3 = Enumerable.Range(min, max).ToList();
Write(list3, list1);
Write(list3, list2);
Console.Read();
// 方法2
for (int i=min;i<=max;i++)
{
if (list1.IndexOf(i)==-1)
{
list1.Add(i);
}
if (list2.IndexOf(i) == -1)
{
list2.Add(i);
}
}
Console.Read();
}
static void Write(List<int> allList, List<int> list)
{
var q = from d in allList
join m in list on d equals m into mr
from mm in mr.DefaultIfEmpty(0)
select mm;
Console.WriteLine(string.Join(",", q.ToArray()));
}
int i = 0;
int length = list1.Count > list2.Count ? list1.Count : list2.Count;
while (i<length)
{
if (i == list1.Count)
{
list1.Add(0);
i++;
continue;
}
if (i == list2.Count)
{
list2.Add(0);
i++;
continue;
}
if (list1[i] != list2[i])
{
if (list1[i] > list2[i])
list1.Insert(i, 0);
else
list2.Insert(i, 0);
length = list1.Count > list2.Count ? list1.Count : list2.Count;
}
i++;
}