美文网首页笔试&&面试经验算法编程
多语言解编程题之数列第N大

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

作者: 剪影Boy | 来源:发表于2017-08-28 15:39 被阅读6次

给予一个整数数列,找出第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大

相关文章

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

    给予一个整数数列,找出第N大的那个数。样例输入:45 67 33 21(换行)2样例输出:45 JavaScrip...

  • 斐波那契数列

    题目 题目一:给定整数N,返回斐波那契数列的第N项,斐波那契数列:1,1,2,3,5,8,12...... 补充题...

  • 每日一题 [11]-斐波拉契数列

    大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39解: 一般是使用递归,因为...

  • LintCode 366 [Fibonacci]

    原题 查找斐波纳契数列中第 N 个数。所谓的斐波纳契数列是指:前2个数是 0 和 1 。第 i 个数是第 i-1 ...

  • 斐波那契数列 青蛙跳台阶

    题目一:求斐波那契数列的第n项。写一个函数,输入n,求斐波那契(Fibonacci)数列的第n 项。斐波那契数列的...

  • 计算题目

    9. 斐波那契数列 描述 输出斐波那契数列的第n项(从0开始,第0项为0)。 公式:f(n) = n, n <= ...

  • 10.斐波那契数列 与 跳台阶问题

    1.斐波那契数列问题 题目:求斐波那契数列的第n项 写一个函数,输入n,求斐波那契(Fibonacci)数列的第n...

  • 面试题10(1):斐波那契数列

    求斐波那契数列的第n项 写一个函数,输入n,求斐波那契数列的第n项。斐波那契数列的定义: 解题思路 递归方法ima...

  • Fibonacci数列相关

    1. Fibonacci数列 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=...

  • 2006北京市小学生程序设计友谊赛详细答案

    第1题 第2题 分析:本题考组合:C(n, 2) = n * (n - 1) / 2 第3题 第4题 第5题 分析...

网友评论

    本文标题:多语言解编程题之数列第N大

    本文链接:https://www.haomeiwen.com/subject/krrgdxtx.html