본문 바로가기

Programing/Algorithm

[LeetCode] 4. Median of Two Sorted Arrays

728x90

 

 

 

https://leetcode.com/problems/median-of-two-sorted-arrays/description/

 

public class Solution {
    public double FindMedianSortedArrays(int[] nums1, int[] nums2)
    {
        int totalLength = nums1.Length + nums2.Length;
        bool even = totalLength % 2 == 0;
        int halfLength = (totalLength) / 2;

        int index1 = 0;
        int index2 = 0;

        double currentNum = 0.0;
        double previousNum = 0.0;

        while (true)
        {
            if ((index1 < nums1.Length) && (index2 < nums2.Length))
            {
                if (nums1[index1] < nums2[index2])
                {
                    currentNum = nums1[index1++];
                }
                else
                {
                    currentNum = nums2[index2++];
                }
            }
            else if (index1 < nums1.Length)
            {
                currentNum = nums1[index1++];
            }
            else if (index2 < nums2.Length)
            {
                currentNum = nums2[index2++];
            }

            if (even)
            {
                if ((index1 + index2) == halfLength)
                {
                    previousNum = currentNum;
                }
                else if ((index1 + index2) == (halfLength + 1))
                {
                    currentNum = (currentNum + previousNum) / 2;
                    break;
                }
            }
            else
            {
                if ((index1 + index2) == (halfLength + 1))
                {
                    break;
                }
            }
        }

        return currentNum;
    }
}

 

 

 

728x90