簡體   English   中英

我該如何解決我的狀況

[英]How can I fix my condition

我想檢查一個數組,如果它的三個值的總和為0。一個條件是不允許三元組(0,0,0)

public static List<List<int>> ThreeSum(int[] num)
    {
        List<List<int>> returnList = new List<List<int>>(); 
        for (int i = 0; i < num.Length; i++)
        {
            for (int j = 0; j < num.Length; j++)
            {
                for (int k = 0; k < num.Length; k++)
                {
                    if (num[i] + num[j] + num[k] == 0 && num[i] <= num[j] && num[j] <= num[k] && (num[i] !=0 && num[j]!= 0 && num[k]!= 0))
                    {
                        List<int> listInt = new List<int>();
                        listInt.Add(num[i]);
                        listInt.Add(num[j]);
                        listInt.Add(num[k]);
                        if (!returnList.Contains(listInt))
                        {
                            returnList.Add(listInt);
                        }
                    }
                }
            }
        }
        return returnList; 
    }

這是我在if (num[i] + num[j] + num[k] == 0 && num[i] <= num[j] && num[j] <= num[k] && (num[i] !=0 && num[j]!= 0 && num[k]!= 0))

因此,我嘗試使用第二種括號: (num[i] !=0 && num[j]!= 0 && num[k]!= 0) ,以確保所有這些條件必須一次滿足。 您可能知道這對我不起作用。 結果中不允許每個零,但只能防止三個零。

一種解決方案是:(-1,0,1)但我不會得到它,因為我的條件不接受其中的零。

鏈接到問題(如果有興趣): https : //leetcode.com/problems/3sum/

您不應該嘗試檢查它們是否都不等於零,而是要檢查其中至少一個不等於零。

所以代替

(num[i] !=0 && num[j]!= 0 && num[k]!= 0)

執行此檢查:

&& (num[i] !=0 || num[j]!= 0 || num[k]!= 0)

更改

&& (num[i] !=0 && num[j]!= 0 && num[k]!= 0)

至:

&& !(num[i] == 0 && num[j] == 0 && num[k] == 0)

您以前的條件是錯誤的; 這意味着i,j和k 必須都不同於0 !(i == 0 || j == 0 || k == 0)是您要執行的操作。

我會這樣:

public static List<List<int>> ThreeSum(int[] num)
{
    List<List<int>> returnList = new List<List<int>>();
    foreach (int i in num)
    {
        foreach (int j in num)
        {
            foreach (int k in num)
            {
                if (i + j + k == 0 && i <= j && j <= k && !(i == 0 || j == 0 || k == 0))
                {
                    returnList.Add(new List<int> { i, j, k });  
                }
            }
        }
    }
    return returnList;
}

如果您有點受虐狂,可以這樣做:

public static List<List<int>> ThreeSum(int[] num)
{
    List<List<int>> returnList = new List<List<int>>();
    foreach (List<int> listInt in num.SelectMany(i => num.SelectMany(j => num.Where(k => i + j + k == 0 && i <= j && j <= k && !(i == 0 || j == 0 || k == 0)).Select(k => new List<int> {i, j, k}).Where(listInt => !returnList.Contains(listInt)))))
    {
        returnList.Add(listInt);
    }
    return returnList;
}

順便說一句,檢查returnList是否包含新列表是無用的,因為它始終為false。 (請參閱第一個代碼的編輯,第二個代碼無法更新。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM