多语言解编程题之数列第N大

给予一个整数数列,找出第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;
} else {
idx = line;
console.log(findBigNum(str, idx));
}
flag = !flag;
});

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;
} else {
$idx = $line;
echo findBigNum($str, $idx) . "\n";
}
$flag = !$flag;
$line = fgets($handle);
}
fclose($handle);

function findBigNum($str, $idx) {
$arr = array_map('intval', explode(' ', $str));
rsort($arr);
return $arr[intval($idx) - 1];
}

C++实现

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;

int findBigNum(string str, string idx) {
stringstream ss(str);
int num;
vector<int> vec;
while(ss >> num) {
vec.push_back(num);
}
sort(vec.rbegin(), vec.rend());
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;
} else {
idx = line;
cout << findBigNum(str, idx) << endl;
}
flag = !flag;
}
return 0;
}

以上。