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

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

输入描述:

一个数组

输出描述:

去重排序后的数组

示例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 s = new ArrayList<>();
        for (String number : numbers) {
            s.add(Integer.parseInt(number));
        }

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

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

        StringBuilder result = new StringBuilder();
        for (Map.Entry 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 
#include 
#include 
#include 

using namespace std;

int main() {
    string input;
    getline(cin, input);
    vector 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 freqMap;
    for (int i = 0; i < s.size(); i++) {
        freqMap[s[i]]++;
    }

    vector> freqVec(freqMap.begin(), freqMap.end());
    sort(freqVec.begin(), freqVec.end(), [](pair &p1, pair &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 
#include 
#include 

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;
}

你可能感兴趣的:(c语言,算法,数据结构)