数组去重和排序 (100%用例)C卷 (Java&&Python&&Node.js&&C语言&&C++)

发布时间:2023年12月28日

给定一个乱序的数组,删除所有的重复元素,使得每个元素只出现一次,并且按照出现的次数从高到低进行排序,相同出现次数按照第一次出现顺序进行先后排序。

输入描述:

一个数组

输出描述:

去重排序后的数组

示例1?输入输出示例仅供调试,后台判题数据一般不包含示例

输入

1,3,3,3,2,4,4,4,5

输出

3,4,1,2,5

备注:

数组大小不超过100

数组元素值大小不超过100

Java版本

import java.util.*;

public class Main{

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String[] numbers = input.split(",");
        List<Integer> s = new ArrayList<>();
        for (String number : numbers) {
            s.add(Integer.parseInt(number));
        }

        Map<Integer, Integer> freqMap = new HashMap<>();
        for (int number : s) {
            freqMap.put(number, freqMap.getOrDefault(number, 0) + 1);
        }

        List<Map.Entry<Integer, Integer>> freqList = new ArrayList<>(freqMap.entrySet());
        Collections.sort(freqList, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        StringBuilder result = new StringBuilder();
        for (Map.Entry<Integer, Integer> entry : freqList) {
            result.append(entry.getKey()).append(",");
        }
        System.out.println(result.toString().substring(0, result.length() - 1));
    }
}

Python版本

from collections import Counter

if __name__ == '__main__':
    s = [int(i) for i in input().split(',')]
    dic = dict(Counter(s))
    dic = dict(sorted(dic.items(), key=lambda x: -x[1]))
    print(",".join([str(i) for i in dic.keys()]))
            

C++版本

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    string input;
    getline(cin, input);
    vector<int> s;
    int value;
    size_t start_pos = 0;
    while ((start_pos = input.find(',')) != string::npos) {
        value = stoi(input.substr(0, start_pos));
        s.push_back(value);
        input.erase(0, start_pos + 1);
    }
    s.push_back(stoi(input)); // 加入最后一个数值

    map<int, int> freqMap;
    for (int i = 0; i < s.size(); i++) {
        freqMap[s[i]]++;
    }

    vector<pair<int, int>> freqVec(freqMap.begin(), freqMap.end());
    sort(freqVec.begin(), freqVec.end(), [](pair<int, int> &p1, pair<int, int> &p2) {
        return p1.second > p2.second;
    });

    for (auto freqPair: freqVec) {
        cout << freqPair.first << ",";
    }
    cout << "\b" << endl;

    return 0;
}

Node.js版本

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
  let numbers = (await readline()).split(',').map(i => parseInt(i))
  const freqMap = new Map()
  for (let number of numbers) {
    if (freqMap.has(number)) {
      freqMap.set(number, freqMap.get(number) + 1)
    } else {
      freqMap.set(number, 1)
    }
  }
  const freqArray = Array.from(freqMap.entries());

  freqArray.sort((a, b) => {
    return b[1] - a[1];
  });

  const result = freqArray.map(entry => entry[0]).join(',');

  console.log(result);


}()

C语言版本

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct number {
    int val;
    int cnt;
} Number;

int cmp(const void *a, const void *b) {
    if (((Number *) a)->cnt != ((Number *) b)->cnt) {
        return ((Number *) b)->cnt - ((Number *) a)->cnt;
    }
    return ((Number *) a)->val - ((Number *) b)->val;
}

int main() {
    setbuf(stdout, NULL);
    char str[1024] = {0};
    gets(str);
    char *p = str;
    Number arr[1024] = {0};
    int arrLen = 0;
    while (p = strtok(p, ",")) {
        int flag = 1;
        for (int i = 0; i < arrLen; ++i) {
            if (arr[i].val == atoi(p)) {
                flag = 0;
                arr[i].cnt++;
                break;
            }
        }
        if (flag == 1) {
            arr[arrLen].val = atoi(p);
            arr[arrLen].cnt = 1;
            arrLen++;
        }
        p = NULL;
    }
    qsort(arr, arrLen, sizeof(arr[0]), cmp);
    for (int i = 0; i < arrLen; ++i) {
        printf("%d,", arr[i].val);
    }
    printf("\b");
    return 0;
}

文章来源:https://blog.csdn.net/qq_43662348/article/details/135260454
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。