C# solution


  • 0
    K
    public class Solution {
        public IList<IList<int>> FourSum(int[] nums, int target) {
            
            IList<IList<int>> list = new List<IList<int>>();
            HashSet<string> elements = new HashSet<string>();
            string s = String.Empty;
            int len = nums.Length;
            Array.Sort(nums);
            
            for (int i=0;i<len-2;i++) {
                for (int m=i+1;m<len-1;m++) {
                    int j = m+1;
                    int k = len-1;
                    while (j < k) {
                        int total = nums[i]+nums[m]+nums[j]+nums[k];
                        if ( total == target) {
                            s = nums[i]+""+nums[m]+""+ nums[j]+""+nums[k];
                            if (!elements.Contains(s))
                            {                        
                                List<int> rowlist = new List<int>();
                                rowlist.Add(nums[i]);
                                rowlist.Add(nums[m]);
                                rowlist.Add(nums[j]);
                                rowlist.Add(nums[k]);
                                list.Add(rowlist);
                                elements.Add(s);
                            }
                            k--;
                            j++;
                        }
                        else if (total < target) j++;
                        else if (total > target) k--;
                    }
                }
            }
            return list;
             
        }
    }
    

Log in to reply
 

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