Game Development
LeetCode 4번 Median of Two Sorted Arrays 본문
문제 링크
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
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.
풀이
두 배열을 하나의 배열로 합친 후 해당 배열에서 가장 중간 값을 찾아주면 됩니다.
여기서 배열의 크기가 짝수일 경우에는 중간의 2개 값을 더하고 절반의 값을 출력해주면 됩니다.
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
nums1.insert(nums1.end(), nums2.begin(), nums2.end());
sort(nums1.begin(), nums1.end());
int arraySize = nums1.size();
int hlafSize = arraySize / 2;
double res = nums1[hlafSize];
if (arraySize % 2 == 0)
{
res += nums1[hlafSize - 1];
res /= 2;
}
return res;
}
};
Time Submitted | Status | RunTime | Memory |
07/25/2021 19:21 | Accepted | 19ms | 89.91MB |
'Algorithms > Leet Code' 카테고리의 다른 글
LeetCode 6번 ZigZag Conversion (0) | 2021.08.04 |
---|---|
LeetCode 5번 Longest Palindromic Substring (0) | 2021.07.25 |
LeetCode 3번 Longest Substring Without Repeating Characters (0) | 2021.07.25 |
LeetCode 2번 Add Two Numbers (0) | 2021.07.25 |
LeetCode 1번 Two Sum (0) | 2021.07.25 |
Comments