LeetCode 179. Largest Number
2016-07-16 13:23
155 查看
Problem: https://leetcode.com/problems/largest-number/
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given
Note: The result may be very large, so you need to return a string instead of an integer.
Thought:
1. turn all int into str, then compare next_now+numStr[i] and numStr[i] + next_now to find the next_now, next_now is the next one to append to the result string, this method is O(n2), only beats 5% cpp submissions
2.sort the numStr with a function, the append them one by one reference: https://discuss.leetcode.com/topic/7286/a-simple-c-solution/2
Code C++ thought 1:
Code C++ thought 2:
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given
[3, 30, 34, 5, 9], the largest formed number is
9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
Thought:
1. turn all int into str, then compare next_now+numStr[i] and numStr[i] + next_now to find the next_now, next_now is the next one to append to the result string, this method is O(n2), only beats 5% cpp submissions
2.sort the numStr with a function, the append them one by one reference: https://discuss.leetcode.com/topic/7286/a-simple-c-solution/2
Code C++ thought 1:
class Solution { public: string largestNumber(vector<int>& nums) { vector<string> numStr; for (int i = 0; i < nums.size(); i++) { numStr.push_back(to_string(nums[i])); } string solve = ""; while (numStr.size() > 1) { vector<string>::iterator next = findNext(numStr); solve += *next; numStr.erase(next); } solve += numStr[0]; if (solve[0] == '0') { return "0"; } return solve; } vector<string>::iterator findNext(vector<string>& nums) { int next = 0; for (int i = 1; i < nums.size(); i++) { string a,b; a = nums[next] + nums[i]; b = nums[i] + nums[next]; next = a > b ? next : i; if (a == b) { next = nums[next].length() <= nums[i].length() ? next : i; } } return nums.begin() + next; } };
Code C++ thought 2:
class Solution { public: string largestNumber(vector<int> &num) { vector<string> numStr; for (int i = 0; i < num.size(); i++) { numStr.push_back(to_string(num[i])); } string solve = ""; sort(numStr.begin(), numStr.end(), [](string &s1, string &s2){return s1 + s2 > s2 + s1;}); for (int i = 0; i < numStr.size(); i++) { solve += numStr[i]; } if (solve[0] == '0') { return "0"; } return solve; } };
相关文章推荐
- JavaScript原型与原型链分析
- timer实现倒计时
- JavaScript高级特性 — 作用域
- PHP cURL
- 哈希查找
- JavaScript 代码风格指南
- 苹果开发者之“企业级账号”的申请流程及总结
- struts2进阶篇(4)
- 加速Android Studio/Gradle构建
- 前端JavaScript规范 非常详细
- 老美:世界到处不太平,唯有北美是天堂
- 模块化JavaScript组件开发指南
- 浅谈 JavaScript DDoS 攻击原理与防御
- 最详细的JavaScript事件使用指南
- 我就是我,不一样的烟火
- 一个简单的JavaScript函数式编程教程
- 2016年7月16日学习 音控&画笔
- Spring MVC入门之编写HelloWorld
- asp.net EF 反向工程 CodeFirst 参数错误异常
- JavaScript中getter/setter的实现