Make a record C# time limit exceed.


  • 0
    Y

    public class Solution {
    public IList<IList<int>> FourSum(int[] nums, int target) {

        var result=new List<IList<int>>();
        
        //check null
        if(nums==null || nums.Length<4)
            return result;
        
        //sort array
        
        Array.Sort(nums);
        
        //need to be unique, so create hash
        
        var hashResult=new Dictionary<int, Dictionary<int,Dictionary<int,int>>>();
        
        int low=2;
        int high=nums.Length-1;
        for(int i=0;i<nums.Length && nums[i] <= target; i++)
        {
            for(int j=i+1; j < nums.Length && nums[j] <= target; j++)
            {
                while(low<high)
                {
                    if(nums[i]+nums[j]+nums[low]+nums[high]==target)
                    {
                        if(hashResult.ContainsKey(nums[i]))
                        {
                            if(hashResult[nums[i]].ContainsKey(nums[j]))
                            {
                                if(!hashResult[nums[i]][nums[j]].ContainsKey(nums[low]))
                                {
                                    hashResult[nums[i]][nums[j]].Add(nums[low],nums[high]);
                                }
                            }
                            else
                            {
                                var dic=new Dictionary<int,int>();
                                dic.Add(nums[low],nums[high]);
                                hashResult[nums[i]].Add(nums[j], dic);
                            }
                        }
                        else
                        {
                            var dic=new Dictionary<int,int>();
                                dic.Add(nums[low],nums[high]);
                            var subDic=new Dictionary<int,Dictionary<int,int>>();
                            subDic.Add(nums[j],dic);
                            hashResult.Add(nums[i],subDic);
                        }
                        
                    }
                    else if(nums[i]+nums[j]+nums[low]+nums[high]<target)
                    {
                        low+=1;
                    }
                    else
                    {
                        high -= 1;
                    }
                }
                
            }
            
        }
        
        foreach(var item in hashResult)
        {
            foreach(var subItem in item.Value)
            {
                foreach(var subSubItem in subItem.Value)
                {
                    var tempList=new List<int>(){item.Key,subItem.Key,subSubItem.Key,subSubItem.Value};
                    result.Add(tempList);
                }
            }
        }
        
        return result;
        
    }
    

    }


Log in to reply
 

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