Optimized C# code


  • 0
    public IList<IList<int>> ThreeSum(int[] nums) {
                int target=0;
                IList<IList<int>> indexs = new List<IList<int>>();
                Array.Sort<int>(nums);
                for (int i = 0; i < nums.Length - 2; i++)
                {
                    if (i == 0 || nums[i] != nums[i - 1])
                    {
                        int lo = i + 1;
                        int hi = nums.Length - 1;
                        int sum = target - nums[i];
                        while (lo < hi)
                        {
                            if (nums[lo] + nums[hi] == sum)
                            {
                                indexs.Add(new List<int>() { nums[i], nums[lo], nums[hi] });
                                while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
                                while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
                                lo++; hi--;
                            }
                            else
                            {
                                if (nums[lo] + nums[hi] < sum)
                                    lo++;
                                else
                                    hi--;
                            }
                        }
                    }
                }
                return indexs;
        }
    

Log in to reply
 

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