30 lines c# code win over 100%


  • 0
    U

    Hi all,
    This is my first post. So if I write anything wrong please let me know.
    Here is my code which used basic 3sum and 3sum closet solution. Very easy to understand if you passed 3sum problems.

    public class Solution 
    {
        public IList<IList<int>> FourSum(int[] nums, int target) 
        {
            List<IList<int>> result = new List<IList<int>>();
            if (nums.Length < 4) return result;
            int sum = 0,len = nums.Length;
            Array.Sort(nums);
            for (int i = 0; i < len - 3; i++)
            {
                for (int j = i + 1; j < len - 2; j++)
                {
                    int lo = j + 1; int hi = len - 1;
                    while (lo < hi)
                    {
                        sum = nums[lo] + nums[hi] + nums[i] + nums[j];
                        if (sum == target)
                        {
                            result.Add(new List<int> { nums[i], nums[j], nums[lo], nums[hi] });
                            while (i < len - 3 && nums[i] == nums[i + 1]) i++;
                            while (j < len - 2 && nums[j] == nums[j + 1]) j++;
                            while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
                            while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
                            lo++;
                            hi--;
                        }
                        else if (target > sum) lo++;
                        else hi--;
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.