LeetCode(中等)四數之和(c#)

題目爲 給定一個包含 n 個整數的數組 nums 和一個目標值 target,判斷 nums 中是否存在四個元素 a,b,c 和 d ,使得 a + b + c + d 的值與 target 相等?找出所有滿足條件且不重複的四元組。
注意:
答案中不可以包含重複的四元組。

示例:
給定數組 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
滿足要求的四元組集合爲:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

很明顯的雙指針,只不過加了一層for循環,代碼如下

		public IList<IList<int>> FourSum(int[] nums, int target)
        {
            IList<IList<int>> li = new List<IList<int>>();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            nums = nums.OrderBy(e => e).ToArray();
            int allCount = nums.Length;
            int left = 0;
            int right = allCount - 1;
            for (int i = 0; i < allCount - 2; i++)
            {
                for (int j = i + 1; j < allCount - 1; j++)
                {
                    left = j + 1;
                    right = allCount - 1;
                    while (left<right)
                    {
                        int sum = nums[i] + nums[j] + nums[left] + nums[right];
                        if (sum>target)
                        {
                            right--;
                        }
                        else if (sum < target)
                        {
                            left++;
                        }
                        else
                        {
                            if (!dic.ContainsKey(nums[i] +""+ nums[j] + "" + nums[left] + "" + nums[right]))
                            {
                                dic.Add(nums[i] + "" + nums[j] + "" + nums[left] + "" + nums[right], "");
                                List<int> liDe = new List<int>() { nums[i], nums[j], nums[left], nums[right] };
                                li.Add(liDe);
                            }
                            right--;
                            left++;
                        }
                    }
                }
            }
            return li;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章