대충이라도 하자

Leetcode - Median of two sorted Arrays 본문

꼬꼬마 개발자 노트/Coding Problems

Leetcode - Median of two sorted Arrays

Sueeeeee
반응형

Hard!!!

 

- too many variables

- think about the edge cases

- array index starts from 0, but length of array is the same with just the number.

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //median 찾기
        //sorted arrays
        int s1= 0, s2=0, index=-1;
        int m = nums1.length;
        int n = nums2.length;
        int [] result = new int[m+n];
        
        while(index != (m+n)/2){
            index++;
            if(s1>m-1) {
                result[index] = nums2[s2++];
                continue;
            }
            if(s2>n-1) {
                result[index] = nums1[s1++];
                continue;
            }
            if(nums1[s1]>nums2[s2]){
                result[index] = nums2[s2++];
            }else {
                result[index] = nums1[s1++];
            }
        }
        
        return (m+n)%2==0? (double) (result[index]+result[index-1])/2 : result[index] ;
        
    }
}

 

 

 

반응형

'꼬꼬마 개발자 노트 > Coding Problems' 카테고리의 다른 글

Design Guru(Day2)  (0) 2023.08.29
Design Gurus(Day1)  (0) 2023.08.28
Blind 75 Must Do Leetcode - Two sum  (0) 2022.06.07
Diagonal Traverse  (0) 2022.03.22
Best Time to Buy and Sell Stock ( Leetcode)  (0) 2022.02.23
Comments