Love丶FFC's Blog

LintCode_easy:中位数

2019-08-30 12:15:15
阅读:447   •   评论:2
标签:,

描述

给定一个未排序的整数数组,找到其中位数。

中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。

数组大小不超过10000

样例

样例 1:

输入:[4, 5, 1, 2, 3]
输出:3
解释:
经过排序,得到数组[1,2,3,4,5],中间数字为3

样例 2:

输入:[7, 9, 4, 5]
输出:5
解释:
经过排序,得到数组[4,5,7,9],第二个(4/2)数字为5

挑战(√)

时间复杂度为O(n)

编程语言:Java

解题思想:

1.直接调用排序的api。

2.根据数组为奇数/偶数判断中位数的位置。

时间复杂度:O(1)

IDE代码如下:

  1. package LintCode_Easy;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class _80 {
  6.  
  7. public static void main(String[] args) {
  8. int[] nums = new int[] {4,5,1,2,3};
  9. Arrays.sort(nums);
  10. if(nums.length%2==0)
  11. System.out.println(nums[nums.length/2-1]);
  12. else
  13. System.out.println(nums[nums.length/2]);
  14. }
  15.  
  16. }
  17.  

LintCode编辑器代码如下:

  1. public class Solution {
  2. public int median(int[] nums) {
  3. Arrays.sort(nums);
  4. if(nums.length%2==0)
  5. return nums[nums.length/2-1];
  6. else
  7. return nums[nums.length/2];
  8. }
  9. }

评论板

共有 2 条评论

  1. Gealpaste

    PCBs in Lake Michigan water revisited cialis online prescription

  2. intuido

    The amplitude of the RD response is decreased by bumetanide to a smaller degree than by furosemide normal dose of viagra

--------查看该分类下最新文章--------
^
新版博客正在完善中!域名:http://www.loveffc:8080,点击跳转,完全移植后将去除端口号。

Copyright © 2018 - 2021 FFC的小站 - 滇 ICP 备 18010780 号 - 1

- Powered by WordPress & AliYun · Theme by FFC -

- Environment by Windows & XAMPP · Designed by WebStorm & VSCode -

已运行:

访问量:490971