給予一個整數(shù)數(shù)列埠褪,找出第N大的那個數(shù)锌历。
樣例輸入:45 67 33 21(換行)2
樣例輸出:45
JavaScript(Node)實現(xiàn)
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實現(xiàn)
<?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++實現(xiàn)
#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;
}
以上。
個人技術(shù)博客 biebu.xin塘装,原文鏈接——多語言解編程題之數(shù)列第N大