C# Accepted solution


  • 0
    A
    public double FindMedianSortedArrays(int[] nums1, int[] nums2)
                {
                    if (nums1 == null && nums2 == null) return 0;
                    var totalLength = 0;
                    if (nums1 != null)
                    {
                        totalLength += nums1.Length;
                    }
                    if (nums2 != null)
                    {
                        totalLength += nums2.Length;
                    }
                    totalLength -= 1;
                    var median = new List<int>() { totalLength / 2};
                    if (totalLength%2 == 1)
                    {
                        median.Add(median[0] + 1);
                    }
                    return FindMedianSortedArrays(nums1?.ToList(), nums2?.ToList(), new List<int>(), median);
                }
    
                public double FindMedianSortedArrays(List<int> nums1, List<int> nums2, List<int> mergedNums, List<int> median)
                {
                    if (mergedNums.Count > median[median.Count - 1])
                    {
                        if (median.Count == 1) return mergedNums[median[0]];
                        return (mergedNums[median[0]] + mergedNums[median[1]])/2d;
                    }
                    if (nums1 == null || nums1.Count == 0)
                    {
                        mergedNums.Add(nums2[0]);
                        nums2.RemoveAt(0);
                    }
                    else if (nums2 == null || nums2.Count == 0)
                    {
                        mergedNums.Add(nums1[0]);
                        nums1.RemoveAt(0);
                    }
                    else
                    {
                        if (nums1[0] < nums2[0])
                        {
                            mergedNums.Add(nums1[0]);
                            nums1.RemoveAt(0);
                        }
                        else
                        {
                            mergedNums.Add(nums2[0]);
                            nums2.RemoveAt(0);
                        }
                    }         
                    return FindMedianSortedArrays(nums1, nums2, mergedNums, median);
    
                }
    

Log in to reply
 

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