无序数组找出其中的第K大的数
2017-09-23 11:46
267 查看
python
补充:
java
# -*- coding: utf-8 -*- """ Created on Sat Sep 23 10:19:24 2017 @author: MLee """ import random def partition(arr, low, high): pivot = arr[low] while low < high: while low < high and arr[high] <= pivot: high -= 1 arr[low] = arr[high] while low < high and arr[low] >= pivot: low += 1 arr[high] = arr[low] arr[low] = pivot return low def get_Kth_max(arr, low, high, k): pos = partition(arr, low, high) if (pos+1) == k: return arr[k-1] elif (pos+1) < k: # k始终为数组中的绝对位置 return get_Kth_max(arr, pos+1, high, k) else: return get_Kth_max(arr, low, pos-1, k) if __name__ == "__main__": k = int(input("(total: 10)> ")) sample = random.choices(range(-50, 50), k=10) print(sample) print(sorted(sample, reverse=True)) print(get_Kth_max(sample, 0, len(sample)-1, k))
补充:
# -*- coding: utf-8 -*- """ Created on Sat Sep 23 10:45:21 2017 @author: MLee """ def get_Kth_max(arr, k): arr = sorted(arr, reverse=True) count = 1 index = 0 for i in range(1, len(arr)): if count == k: break if arr[i] != arr[index]: index = i count += 1 return arr[index] if __name__ == "__main__": k = int(input("> ")) arr = list(map(int, input("> ").split())) print(sorted(arr, reverse=True)) print(get_Kth_max(arr, k))
java
package edu.ccnu; import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class Kth { public static int partition(int[] arr, int low, int high){ int pivot = arr[low]; while(low < high){ while(low < high && arr[high] <= pivot){ high--; } arr[low] = arr[high]; while(low < high && arr[low] >= pivot){ low++; } arr[high] = arr[low]; } arr[low] = pivot; return low; } public static int getKthMax(int[] arr, int low, int high, int k){ int pos = partition(arr, low, high); if((pos+1) == k){ return arr[k-1]; }else if((pos+1) < k){ return getKthMax(arr, pos+1, high, k); }else{ return getKthMax(arr, low, pos-1, k); } } public static void main(String[] args) { Random rand = new Random(System.currentTimeMillis()); int[] sample = new int[8]; // int k = rand.nextInt(sample.length); Scanner sc = new Scanner(System.in); System.out.print("> "); int k = sc.nextInt(); for(int i = 0; i < sample.length; i++){ sample[i] = rand.nextInt(100); } System.out.println(Arrays.toString(sample)); System.out.println(getKthMax(sample, 0, sample.length-1, k)); Arrays.sort(sample); System.out.println(Arrays.toString(sample)); } }
相关文章推荐
- 给定一个无序整形数组,找出其中所以三个数之和为0的所有组合
- 面试题—— 找出一个无序整型数组中第k大的数。
- 面试题:在一个数组中有0-99之间的整数101个(数组无序),用高效方法找出其中的唯一的重复元素!
- 一个无序整数数组,数组元素大于5个,请用一种高效的算法找出其中最大的5个值.
- 找出无序数组中第k小的数
- java 实现从无序数组中 找出第k大的数, 无序数组充许有重复元素
- 算法之每日一题:找出无序数组中第k大的数字
- 算法导论:快速找出无序数组中第k小的数
- 在一个无序整型数组中找出第k小的数字
- 由无序数组中找到第K 大的元素
- 在一个无序的数组中找出最长的等差数列
- 有 n 个无序整数( n>10000), 则找出其中最大的 M 个数字( 5<M<10), 所需要的最小时间复杂度为:
- 寻找无序数组中第k大的数
- 数组a[N],存放了N个数,其中某个数重复一次。 写一个函数,找出被重复的数字.时间复杂度必须为o(N)
- (google面试题)找出无序数组中连接和最大排序
- Java面试题:1-100之间的数,被放在数组a[99]中,有一个数没有包含在其中,用java代码找出这个数
- 寻找单个无序数组中第K小的数字
- 无序整数数组中找第k大的数
- 100亿个无序数,给定里面其中一个数A,找出与A大小相差最小的各10个数
- 一个无序数组中第K大的元素