首页 > 试题广场 >

查找第K大的元素

[编程题]查找第K大的元素
  • 热度指数:11087 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定一个无序的整型数组A[n],数组大小大于等于3,允许有值相同的元素;请设计算法找到该数组排序后第三大的元素值并输出.

输入描述:
一个非空的整数数组(至少有3个元素,可正可负)


输出描述:
第三大的元素值
示例1

输入

[1,2,3,4,5]

输出

3
示例2

输入

[1,1,2,2,3]

输出

2
示例3

输入

[6,5,4,4,1,2]

输出

4
偷懒写法
nums = eval(raw_input().strip())
nums.sort()
print nums[-3]

堆排序
from collections import deque
class Solution(object):
    def heap_adjust(self, lyst, start, end):
        temp = lyst[start]
        i = start
        j = 2*i
        while j <= end:
            if j < end and lyst[j] < lyst[j+1]:
                j += 1
            if temp < lyst[j]:
                lyst[i] = lyst[j]
                i = j
                j = 2*i
            else:
                break
        lyst[i] = temp
        
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        nums = deque(nums)
        nums.appendleft(0)
        
        n = len(nums)-1
        f = n / 2
        for i in range(f, 0, -1):
            self.heap_adjust(nums, i, n)
        
        res = None
        for i in range(n, n-k, -1):
            res = nums[1]
            nums[1], nums[i] = nums[i], nums[1]
            self.heap_adjust(nums, 1, i-1)
        return res
nums = eval(raw_input().strip())
s = Solution()
print s.findKthLargest(nums, 3)
编辑于 2020-02-27 13:21:07 回复(0)
二分查找排序
a = input()
N = len(a)
for i in range(N):
    temp = a[i]
    left, right = 0, i-1
    while left <= right:
        mid = left + (right-right)//2
        if a[mid]>temp:
            right = mid - 1
        else:
            left = mid + 1
        a[right+2:i+1] = a[right+1:i]
        a[right+1] = temp
print a[-3]
发表于 2019-10-29 22:48:52 回复(0)
arr = input()
numbers = list(map(str, arr.split(',')))
numbers[0] = numbers[0][1:]
numbers[-1] = numbers[-1][:-1]
numbers = list(map(int, numbers))
numbers = sorted(numbers) print(numbers[-3])
发表于 2019-09-02 16:36:39 回复(0)
""""
求第k大值
"""

if __name__ == "__main__":
    a = eval(input().strip())
    print(sorted(a)[-3])

发表于 2019-07-12 13:09:17 回复(1)