c++ - 排序得到最大数
问题描述
给定一个非负整数列表,我必须对它们进行排列,使它们在词法连接时形成最大的数字,并将结果数字作为字符串返回。
输入为:[3, 30, 34, 5, 9]
我试图手动遍历数组,但我不明白我错在哪里。所有元素都按我的预期交换,但 3 和 30 没有交换。谁能找到代码中的错误?
#include <iostream>
#include <vector>
int main(){
std::vector<int>b={ 3, 30, 34, 5, 9 };
for(int i=0 ;i<b.size()-1; i++){//i moves from 0 to 3 and picks the ith element
for(int j=i+1; j<b.size(); j++){
/*j moves from i+1 to 4 and compares
the strings formed by appending int turned strings b[i] and b[j]
in two possible orders such as "b[i]b[j]" and "b[j]b[i]"
*/
std::string str1,str2,str3,str4;
str1 = to_string(b[i]);
str2 = to_string(b[j]);
str3 = str1.append(str2);
str4 = str2.append(str1);
if(stoi(str4)>stoi(str3)){
// if loop swaps if "b[j]b[i]" is greater than "b[i]b[j]"
swap(b[i],b[j]);
}
}
}
std::string s="";
for(int i=0; i<b.size(); i++){//creates string s from sorted array
s.append(to_string(b[i]));
}
std::cout<<s;/*prints largest string that is possible by sorting the elements of array*/
return 0;
}
预期:9534330
实际:9534303
解决方案
你的错误是你,swap(b[i],b[j]);
但你比较A
的值。很快,A和B数组就变得不相关了。只需使用一个数组。交换您从中比较值的同一数组。
它会起作用的。令人惊讶的是,这种方法感觉有点令人费解,但确实如此。
编辑:
还,
str1.append(str2);
str2.append(str1);
不要做你认为/期望它做的事情。第一行修改str1
. 你需要解决这个问题,但我不会做你的全部作业。
推荐阅读
- google-cloud-platform - Google Cloud - 数据共享选项
- python - 图像噪声处理和边缘方向确定
- node.js - res.sendFile 命令nodejs中的错误
- ios - 什么是 Swift 中的 `_ArrayBuffer` 以及我应该如何以及何时使用它?
- node.js - 通过 HTTP POST 请求进行跨容器通信
- r - 尝试重新创建 cor() 函数时找不到“x”或“y”
- html - 如何从 url 中删除 .html 扩展名
- java - 错误:Ionic 上 JDK 1.8 或更高版本的要求检查失败
- r - 使用 rvest 和特定错误抓取数据
- android - 如何从android中优雅的数字按钮获取固定值?