给予一个整数数列,找出第N大的那个数。
样例输入:45 67 33 21(换行)2
样例输出:45
JavaScript(Node)实现
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let flag = true;
let str, idx;
rl.on('line', function(line) {
if (flag) {
str = line;
flag = false;
} else {
idx = line;
console.log(findBigNum(str, idx));
flag = true;
}
});
function findBigNum(str, idx) {
let arr = str.split(' ').map(val => +val);
arr.sort((a, b) => b - a);
return arr[idx - 1];
}
PHP实现
<?php
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
$flag = true;
while ($line !== "") {
if ($flag) {
$str = $line;
$flag = false;
} else {
$idx = $line;
echo findBigNum($str, $idx) . "\n";
}
$line = fgets($handle);
}
fclose($handle);
function findBigNum($str, $idx) {
$arr = array_map("intval", explode(" ", $str));
rsort($arr);
return $arr[$idx - 1];
}
C++实现
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int findBigNum(string str, string idx) {
stringstream iss(str);
int number;
vector<int> vec;
while(iss >> number) {
vec.push_back(number);
}
sort(vec.begin(), vec.end(),
[](const int a, const int b) {
return b < a;
}
);
return vec[atoi(idx.c_str()) - 1];
}
int main() {
string line;
bool flag = true;
string str, idx;
while (getline(cin, line)) {
if (flag) {
str = line;
flag = false;
} else {
idx = line;
cout << findBigNum(str, idx) << endl;
flag = true;
}
}
return 0;
}
以上。
个人技术博客 biebu.xin,原文链接——多语言解编程题之数列第N大
网友评论