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;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章