描述
给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
python code
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
self.quick_sort(nums, 0, len(nums) - 1)
if len(nums) % 2 == 0:
i = len(nums) / 2 - 1
else:
i = len(nums) / 2
return nums[i]
def position(self, nums, start, end):
i = start
j = end
povit = nums[i]
while i < j:
while i < j and nums[j] >= povit:
j -= 1
if i < j:
nums[i] = nums[j]
while i < j and nums[i] <= povit:
i += 1
if i < j:
nums[j] = nums[i]
nums[i] = povit
return i
def quick_sort(self, nums, start, end):
if start < end:
mid = self.position(nums, start, end)
self.quick_sort(nums, start, mid -1)
self.quick_sort(nums, mid + 1, end)
说明
使用快速排序算法