LintCode:中位数

LintCode:中位数

Python

class Solution:
    """ @param nums: A list of integers. @return: An integer denotes the middle number of the array. """
    def median(self, nums):
        # write your code here
        nums = sorted(nums)
        m = len(nums)

        if m%2 == 1:
            return nums[m/2]
        else:
            return nums[m/2-1]

Java

public class Solution {
    /** * @param nums: A list of integers. * @return: An integer denotes the middle number of the array. */
    public int median(int[] nums) {
        // write your code here

        Arrays.sort(nums);
        int m = nums.length;
        if (m%2==0){
            return nums[m/2 - 1];
        }
        else{
            return nums[m/2];
        }
    }
}

你可能感兴趣的:(LintCode:中位数)