Leetcode 179. Largest Number (Medium) (cpp)
2016-09-22 13:48
441 查看
Leetcode 179. Largest Number (Medium) (cpp)
Tag: Sort
Difficulty: Medium
/*
179. Largest Number (Medium)
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.
*/
class Solution {
public:
string largestNumber(vector<int>& nums) {
string res;
sort(nums.begin(), nums.end(), comp);
if (nums[0] == 0) return "0";
for (int num : nums)
res += to_string(num);
return res;
}
static bool comp(int i, int j) {
return to_string(i) + to_string(j) > to_string(j) + to_string(i);
}
};
Tag: Sort
Difficulty: Medium
/*
179. Largest Number (Medium)
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.
*/
class Solution {
public:
string largestNumber(vector<int>& nums) {
string res;
sort(nums.begin(), nums.end(), comp);
if (nums[0] == 0) return "0";
for (int num : nums)
res += to_string(num);
return res;
}
static bool comp(int i, int j) {
return to_string(i) + to_string(j) > to_string(j) + to_string(i);
}
};
相关文章推荐
- Leetcode 375. Guess Number Higher or Lower II (Medium) (cpp)
- Leetcode 268. Missing Number (Medium) (cpp)
- leetCode 179. Largest Number 字符串排序 | Medium | lambda表达式
- Leetcode 179. Largest Number (Medium) (java)
- Leetcode 92. Reverse Linked List II (Medium) (cpp)
- Leetcode 148. Sort List (Medium) (cpp)
- Leetcode 151. Reverse Words in a String (Medium) (cpp)
- Leetcode 240. Search a 2D Matrix II (Medium) (cpp)
- Leetcode 275. H-Index II (Medium) (cpp)
- Leetcode 2. Add Two Numbers (Medium) (cpp)
- [Leetcode 136, Medium] Single Number I
- Leetcode 325. Maximum Size Subarray Sum Equals k (Medium) (cpp)
- Leetcode 277. Find the Celebrity (Medium) (cpp)
- [Leetcode 200, medium] Number of Islands
- Leetcode 209. Minimum Size Subarray Sum (Medium) (cpp)
- Leetcode 73. Set Matrix Zeroes (Medium) (cpp)
- Leetcode 53. Maximum Subarray (Medium) (cpp)
- Leetcode 298. Binary Tree Longest Consecutive Sequence (Medium) (cpp)
- Leetcode 79. Word Search (Medium) (cpp)
- Leetcode 331. Verify Preorder Serialization of a Binary Tree (Medium) (cpp)