반응형

문제

  • Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
    Input: nums1 = [1,3], nums2 = [2]
    Output: 2.00000
    Explanation: merged array = [1,2,3] and median is 2.
    
    Example 2:
    • nums1.length == m
    • nums2.length == n
    • 0 <= m <= 1000
    • 0 <= n <= 1000
    • 1 <= m + n <= 2000
    • -106 <= nums1[i], nums2[i] <= 106
  • Constraints:
  • Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
  • Example 1:
  • The overall run time complexity should be O(log (m+n)).

 

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

 

 

풀이

이미 정렬된 두개의 배열을 준다고 하여, 그냥 하나로 합쳐서 풀었다.

 

 

 

코드

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int i = 0, j = 0, z = 0;
        
        int[] nums = new int[nums1.length + nums2.length];
        while (i < nums1.length && j < nums2.length) {
            nums[z++] = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];
        }
         
        if (i == nums1.length) {
            for (; z < nums.length; z++) {
                nums[z] = nums2[j++];
            }
        }
        else {
            for (; z < nums.length; z++) {
                nums[z] = nums1[i++];
            }
        }
        
         
        if (nums.length % 2 == 0) {
        	return (double)(nums[nums.length / 2 - 1] + nums[nums.length / 2]) / 2;
        }
        else {
        	return nums[nums.length / 2]; 
        }
    }
}

 

 

결과

Runtime: 4 ms, faster than 60.76% of Java online submissions for Median of Two Sorted Arrays.
Memory Usage: 49.5 MB, less than 13.27% of Java online submissions for Median of Two Sorted Arrays.

 

반응형

'LeetCode' 카테고리의 다른 글

6. Zigzag Conversion  (1) 2024.11.05
5. Longest Palindromic Substring  (0) 2022.02.14
3. Longest Substring Without Repeating Characters 수정  (0) 2022.01.21
3. Longest Substring Without Repeating Characters  (0) 2022.01.16
9. Palindrome Number  (0) 2022.01.16

+ Recent posts