![](/img/trans.png)
[英]Finding if a target number is the sum of two numbers in an array via LINQ and get the and Indices
[英]Finding if a target number is the sum of two numbers in an array via LINQ
基本解決方案如下所示:
bool sortTest(int[] numbers, int target)
{
Array.Sort(numbers);
for(int i = 0; i < numbers.Length; i++)
{
for(int j = numbers.Length-1; j > i; j--)
{
if(numbers[i] + numbers[j] == target)
return true;
}
}
return false;
}
現在我對LINQ很新,但這是我到目前為止寫的:
var result = from num in numbers
where numbers.Contains(target -num)
select num;
if (result.Count() > 0)
return true;
return false;
現在我遇到以下示例遇到的問題:
數組:1,2,4,5,8
目標:16
它應該返回false,但它正在捕獲16-8 = 8。 那么我怎么去不讓它在包含檢查中注意到它? 或者我可以在查詢中每次創建第二個數組,但不包含我正在使用的數字(從而解決問題)?
提前致謝。
這是你在找什么?
var result = from n1 in numbers
from n2 in numbers
where n1 != n2 && n1 + n2 == target
select new { n1, n2 };
[編輯]這將返回兩次匹配,並忽略數組在數組中重復的情況。 您無法使用表達式語法處理這些情況,因為您無法訪問匹配項的索引,但您可以這樣做:
var result = numbers.Select((n1, idx) =>
new {n1, n2 = numbers.Take(idx).FirstOrDefault(
n2 => n1 + n2 == target)}).Where(pair => pair.n2 != 0);
只要你的數組中沒有任何零。
[進一步思考編輯]
完美的混合解決方案:
var result = from item in numbers.Select((n1, idx) =>
new {n1, shortList = numbers.Take(idx)})
from n2 in item.shortList
where item.n1 + n2 == target
select new {n1 = item.n1, n2};
我一般要解決這個問題,首先要寫一個“選擇器”。
public static IEnumerable<IEnumerable<T>> Chooser<T>(this IList<T> sequence, int num)
{ ... left as an exercise ... }
選擇器的輸出是一系列序列。 每個子序列的長度為num,由選自原始序列的元素組成。 因此,如果您通過{10,30,20,50}作為序列而3作為num,您將獲得序列序列:
{10, 30, 20}, {10, 30, 50}, {10, 20, 50}, {30, 20, 50}
結果是。
一旦你編寫了Chooser,問題就變得容易了:
var results =
from subsequence in numbers.Chooser(2)
where subsequence.Sum() == target
select subsequence;
現在你可以解決其他尺寸的子序列的問題,而不僅僅是對。
寫選配是有點棘手,但它不是太難 。
為了改進pdr的回復並解決注釋中提到的問題,您可以使用重載的Select方法來比較項的索引並確保唯一性。
public bool sortTest(int[] numbers, int target)
{
var indexedInput = numbers.Select((n, i) => new { Number = n, Index = i });
var result = from x in indexedInput
from y in indexedInput
where x.Index != y.Index
select x.Number + y.Number == target;
return result.Any(item => item);
}
或者用點符號表示:
var result = numbers.Select((n, i) => new { Number = n, Index = i })
.SelectMany(
x => indexedInput,
(x, y) => new { x = x, y = y })
.Where(item => item.x.Index != item.y.Index)
.Select(item => item.x.Number + item.y.Number == target);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.