LeetCode - 4. 寻找两个正序数组的中位数
生活随笔
收集整理的這篇文章主要介紹了
LeetCode - 4. 寻找两个正序数组的中位数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
題目描述
給定兩個大小為 m 和 n 的正序(從小到大)數組?nums1?和?nums2。請你找出并返回這兩個正序數組的中位數。
輸入樣例
示例 1:
輸入:nums1 = [1,3], nums2 = [2]
輸出:2.00000
解釋:合并數組 = [1,2,3] ,中位數 2
示例 2:
輸入:nums1 = [1,2], nums2 = [3,4]
輸出:2.50000
解釋:合并數組 = [1,2,3,4] ,中位數 (2 + 3) / 2 = 2.5
示例 3:
輸入:nums1 = [0,0], nums2 = [0,0]
輸出:0.00000
示例 4:
輸入:nums1 = [], nums2 = [1]
輸出:1.00000
示例 5:
輸入:nums1 = [2], nums2 = []
輸出:2.00000
解題思路
將兩個數組合并成一個數組,去中間的兩個數或者一個數。
解題代碼
//#include <vector> //#include <iostream>using namespace std;class Solution { public:double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) {int n1 = nums1.size();int n2 = nums2.size();int n = n1 + n2;int mergeVector[n];int index = 0;int index1 = 0;int index2 = 0;while (index <= n/2 && index1 < n1 && index2 < n2) {if (nums1[index1] < nums2[index2]) {mergeVector[index] = nums1[index1];index1++;} else {mergeVector[index] = nums2[index2];index2++;}index++;}while (index <= n/2 && index1 < n1) {mergeVector[index] = nums1[index1];index1++;index++;}while (index <= n/2 && index2 < n2) {mergeVector[index] = nums2[index2];index2++;index++;}if (n%2 ==0){return ((double) (mergeVector[n/2]+mergeVector[n/2-1]))/2;} else{return mergeVector[n/2];}} }; //int main() { // // Solution solution; // vector<int> nums1; // vector<int> nums2; // nums2.push_back(1); // nums2.push_back(2); // nums1.push_back(3); // // double res = solution.findMedianSortedArrays(nums1,nums2); // cout << res; // return 0; // //}解題結果
總結
以上是生活随笔為你收集整理的LeetCode - 4. 寻找两个正序数组的中位数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows上mount NFS V4
- 下一篇: 【postgresql初始化失败】ini