鍍金池/ 問(wèn)答/C#/ A集合基于B集合,去掉B集合中存在的值

A集合基于B集合,去掉B集合中存在的值

        List<int> A = new List<int>() { 1, 1, 2, 3, 3 };
        List<int> B = new List<int>() { 1, 3 };
        想把A的值基于B去掉
        變成
        List<int> A = new List<int>() {  1, 2, 3};
        應(yīng)該用什么方法來(lái)處理這種情況
回答
編輯回答
孤客

https://www.cnblogs.com/wdw31...
PS:踩人需謹(jǐn)慎,別把自己弄成個(gè)笑話(huà)。

List<int> a = new List<int>() { 1, 1, 2, 3, 3 };
List<int> b = new List<int>() { 1, 3 };
var c = a.Intersect(b).Union(a.Except(b)).ToList();
// 按照需要自行決定是否和如何排序
c.Sort();
// 現(xiàn)在,c集合就是你想要的(按照題面來(lái)說(shuō))
// 大膽做個(gè)猜測(cè),題主想要的應(yīng)該不是這樣的集合吧?
// 可能只是想要差集,做個(gè)題主自行抉擇。


補(bǔ)充內(nèi)容:


  1. 無(wú)知的人永遠(yuǎn)都不可理喻;
  2. 題主勿怪,畢竟你也沒(méi)描述要不要去重;
  3. 某些人,我和題主坐等你的道歉;
  4. 想想有些人需要?jiǎng)e人給他嚼爛了和著唾液才肯咽下去,就覺(jué)得惡心。
List<int> a = new List<int>() { 1, 1, 1, 2, 2, 3, 3, 3 };
List<int> b = new List<int>() { 1, 3 };
a.Sort();
b.Sort();
// 去重的實(shí)現(xiàn)
List<int> c = a.Intersect(b).Distinct().Union(a.Except(b)).ToList();
List<int> d = a.Select(i => i).ToList();
// 不去重的實(shí)現(xiàn)
b.ForEach(item => d.RemoveAt(d.FindIndex(aItem => aItem == item)));
c.Sort();
d.Sort();
Console.WriteLine("集合a=" + string.Join(",", a));
Console.WriteLine("集合b=" + string.Join(",", b));
Console.WriteLine("集合c=" + string.Join(",", c));
Console.WriteLine("集合d=" + string.Join(",", d));
2017年3月9日 06:33
編輯回答
懶豬

先排序,然后按順序同時(shí)遍歷A和B即可。偽代碼:

A.sort();
B.sort();
List<int> result = ...;
for (int i = 0, j = 0; i < A.length && j < B.length; i++) {
    while (A[i] > B[j] && j < B.length) {
        j++;
    }
    if (j < B.length && A[i] == B[j]) {
        add A[i] to result;
        j++;
    }
}
2017年8月4日 00:05