整型数组按个位值排序
给定一个非空数组(列表),其元素数据类型为整型,请按照数组元素十进制最低位从小到大进行排序,十进制最低位相同的元素,相对位置保持不变。
当数组元素为负值时,十进制最低位等同于去除符号位后对应十进制值最低位。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> split(const string &str, const string &pattern) {
vector<int> resVec;
if ("" == str) {
return resVec;
}
string strs = str + pattern;
size_t pos = strs.find(pattern);
size_t size = strs.size();
while (pos != string::npos) {
string x = strs.substr(0, pos);
resVec.push_back(stoi(x));
strs = strs.substr(pos + 1, size);
pos = strs.find(pattern);
}
return resVec;
}
void mySort(vector<int> &arr) {
int t = 0;
for (int i = 1; i < arr.size(); ++i) {
for (int j = 0; j < arr.size() - i; ++j) {
if (abs(arr[j]) % 10 > abs(arr[j + 1]) % 10) {
t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
}
}
int main() {
string s;
cin >> s;
vector<int> arr;
arr = split(s, ",");
mySort(arr);
for (int i = 0; i < arr.size() - 1; ++i) {
cout << arr[i] << ",";
}
cout << arr[arr.size() - 1] << endl;
return 0;
}
import sys
for line in sys.stdin:
nums = line.strip().split(",")
def radix(nums):
temp_dict = {0:[],1:[],2:[],3:[],4:[],5:[],6:[],7:[],8:[],9:[]}
for num in nums:
abs_num = abs(int(num))
temp_dict[abs_num % 10].append(num)
temp_list = []
for i in range(10):
temp_list += temp_dict[i]
nums = temp_list
return ",".join(temp_list)
print(radix(nums))
#include <bits/stdc++.h>
#define MAXN 1234
using namespace std;
int a[MAXN];
vector<int> res[10];
string str;
int str_to_int(string src) {
if (src.size() == 0) {
return 0;
}
int idx = 0;
int res = 0;
if (src[0] == '-' || src[0] == '+') {
idx++;
}
for (; idx < (int)src.size(); idx++) {
res *= 10;
res += src[idx] - '0';
}
if (src[0] == '-') {
return -res;
}
return res;
}
int input(int src[]) {
int len = 0;
string s = "";
cin >> str;
for (int i = 0; i < (int)str.size(); i++) {
if (str[i] == ',') {
src[len++] = str_to_int(s);
s = "";
} else {
s += str[i];
}
}
if (s != "") {
src[len++] = str_to_int(s);
}
return len;
}
void init() {
memset(a, 0, sizeof(a));
for (int i = 0; i < 10; i++) {
res[i].clear();
}
}
int main() {
init();
int len = input(a);
for (int i = 0; i < len; i++) {
if (a[i] < 0) {
res[(-a[i]) % 10].push_back(a[i]);
} else {
res[a[i] % 10].push_back(a[i]);
}
}
bool fir = true;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (int)res[i].size(); j++) {
if (fir == true) {
cout << res[i][j];
fir = false;
} else {
cout << "," << res[i][j];
}
}
}
cout << "\n";
return 0;
}
if __name__ == "__main__":
# 读取第一行的n
input_str = input().split(",")
output = sorted(input_str,key=lambda x: x[-1])
print(",".join(output))
查看23道真题和解析
顺丰集团工作强度 406人发布