프로그래밍 공방

[LeetCode] Median of Two Sorted Arrays 본문

개발/문제해결

[LeetCode] Median of Two Sorted Arrays

hyosupsong 2021. 1. 1. 16:05

문제

leetcode.com/problems/median-of-two-sorted-arrays/

 

Median of Two Sorted Arrays - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제해결방법

이 문제는 정렬된 두 배열이 주어지고 두 배열을 합쳤을때 중앙값을 구하는 문제였다.

각 배열에 시작 인덱스를 두고 각 배열의 원소들을 앞에서부터 비교해가면서 두 배열을 합친 길이의 중간 개수까지 세준다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package leetcode;
 
public class Solution_MedianofTwoSortedArrays {
 
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int N = nums1.length;
        int M = nums2.length;
        int i1 = 0, i2 = 0;
        int count = 0;
        int index = (M+N)>>1;
        double mid = 0;
        if((N+M)%2==0) index--;
        while(count<=index) {
            if(i1<nums1.length && i2<nums2.length) {
                if(nums1[i1]<nums2[i2]) {
                    mid = nums1[i1];
                    i1++;
                }
                else {
                    mid = nums2[i2];
                    i2++;
                }
            } else if(i1>=nums1.length && i2<nums2.length) {
                mid = nums2[i2];
                i2++;
            } else if (i1<nums1.length && i2>=nums2.length) {
                mid = nums1[i1];
                i1++;
            }
            count++;
        }
        if((N+M)%2==0) {
            if(i1<nums1.length && i2<nums2.length) {
                if(nums1[i1]<nums2[i2]) mid += nums1[i1];
                else mid += nums2[i2];
            }
            else if(i1>=nums1.length && i2<nums2.length) mid += nums2[i2];
            else if (i1<nums1.length && i2>=nums2.length) mid += nums1[i1];
            mid /= 2.0d;
        }
        return mid;
    }
    
    public static void main(String[] args) {
        int[] nums1 = {};
        int[] nums2 = {1};
        System.out.println(findMedianSortedArrays(nums1, nums2));
    }
}
cs


코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.