LeetCode题解(Golang实现)--Median of Two Sorted Arrays
来源:互联网 发布:java list remove方法 编辑:程序博客网 时间:2024/06/04 20:08
题目
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]nums2 = [2]The median is 2.0
Example 2:
nums1 = [1, 2]nums2 = [3, 4]The median is (2 + 3)/2 = 2.5
解题思路
最简单的就是将两个数组合并成一个,然后根据中位数的概念计算中位数,当长度n为奇数时,中位数为x((n+1)/2),当长度n为偶数是,中位数为x((n/2)+x(n/2+1))/2
答案
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { i, j := 0, 0 nums3 := []int{} for i < len(nums1) && j < len(nums2) { if nums1[i] < nums2[j] { nums3 = append(nums3, nums1[i]) i = i + 1 } else { nums3 = append(nums3, nums2[j]) j = j + 1 } } if i < len(nums1) { for ; i < len(nums1); i++ { nums3 = append(nums3, nums1[i]) } } if j < len(nums2) { for ; j < len(nums2); j++ { nums3 = append(nums3, nums2[j]) } } lenSums3 := len(nums3) if lenSums3%2 == 0 { return (float64(nums3[lenSums3/2-1]) + float64(nums3[lenSums3/2])) / 2.0 } else { return float64(nums3[(lenSums3+1)/2-1]) }}
阅读全文
0 0
- LeetCode题解(Golang实现)--Median of Two Sorted Arrays
- leetcode 4 golang Median of Two Sorted Arrays
- [LeetCode题解004]Median of Two Sorted Arrays
- LeetCode 题解(66): Median of Two Sorted Arrays
- leetcode题解||Median of Two Sorted Arrays问题
- [Leetcode题解]004 Median of Two Sorted Arrays
- LeetCode题解——4Median of Two Sorted Arrays
- LeetCode题解--4. Median of Two Sorted Arrays
- LeetCode题解:4. Median of Two Sorted Arrays
- Leetcode题解4.Median of Two Sorted Arrays
- LeetCode题解-4-Median of Two Sorted Arrays
- LeetCode题解–4. Median of Two Sorted Arrays
- leetcode题解Java | 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays LeetCode题解
- LeetCode题解(4)--Median of Two Sorted Arrays
- leetcode题解-4. Median of Two Sorted Arrays
- LeetCode题解系列--4. Median of Two Sorted Arrays
- leetcode题解-4. Median of Two Sorted Arrays
- 输入一个链表,反转链表后,输出链表的所有元素。
- Learning the interface
- javamail模拟邮箱功能--邮件回复-中级实战篇【邮件回复方法】(javamail API电子邮件实例)
- 树莓派3b安装raspbian系统
- Python网络爬虫学习笔记(第一周)
- LeetCode题解(Golang实现)--Median of Two Sorted Arrays
- 如何防止头文件被重复包含、嵌套包含
- Qt求学路2
- Windows Server 2016 配置指南 之 FTP环境搭建篇踩到的坑
- thinkphp操作mysql之打印sql语句
- GMail API for Python
- 【Web】Flex布局
- Oracle 如何将一个字段拆分成表
- Android studio 自动导入(全部)包 import