Pintia题解——7-7出租

7-7 出租

原题:

一时间网上一片求救声,急问这个怎么破。其实这段代码很简单,index数组就是arr数组的下标,index[0]=2 对应 arr[2]=1index[1]=0 对应 arr[0]=8index[2]=3 对应 arr[3]=0,以此类推…… 很容易得到电话号码是18013820100

本题要求你编写一个程序,为任何一个电话号码生成这段代码 —— 事实上,只要生成最前面两行就可以了,后面内容是不变的。

输入格式:

输入在一行中给出一个由11位数字组成的手机号码。

输出格式:

为输入的号码生成代码的前两行,其中arr中的数字必须按递减顺序给出。

.

解题思路:

  1. 使用 new Set(input) 构造一个去重的 Set 对象。
  2. 将 Set 对象转换为数组,使用扩展运算符 [... new Set(input)]
  3. 对数组进行排序,使用 sort((a, b) => { return b - a }),按照降序排列。
  4. 创建一个新数组 arr,用于存储排好序的元素。
  5. 将输入字符串 input 转换为字符数组,使用 Array.from(input)
  6. 使用 map 方法遍历字符数组,对每个字符调用回调函数,假设参数为 index
  7. 在回调函数内部,利用 arr.indexOf(index) 找到字符在 arr 数组中的索引

.

JavaScript(node)代码:

const r = require("readline");
const rl = r.createInterface({
    
    
    input: process.stdin
});
let buf = []
rl.on('line', (input) => {
    
    
    buf.push(input);
});
rl.on('close', () => {
    
    
    const arr = [... new Set(buf[0])].sort((a, b) => {
    
     return b - a });
    const index = Array.from((buf[0])).map(index => arr.indexOf(index))
    console.log(`int[] arr = new int[]{
     
     ${
      
      arr.join(",")}};`);
    console.log(`int[] index = new int[]{
     
     ${
      
      index.join(",")}};`);
});

.

复杂度分析:

时间复杂度:O(1)
空间复杂度:O(n)

猜你喜欢

转载自blog.csdn.net/Mredust/article/details/132914755
7-7