将数组重新排序以构造最小值-LintCode
来源:互联网 发布:手机淘宝店招280 50px 编辑:程序博客网 时间:2024/05/21 09:03
给定一个整数数组,请将其重新排序,以构造最小值。
注意事项:
The result may be very large, so you need to return a string instead of an integer.
样例
给定 [3, 32, 321],通过将数组重新排序,可构造 6 个可能性数字:
3+32+321=3323213+321+32=33213232+3+321=32332132+321+3=323213321+3+32=321332321+32+3=321323
其中,最小值为 321323,所以,将数组重新排序后,该数组变为 [321, 32, 3]。
挑战 :
在原数组上完成,不使用额外空间。
#ifndef C379_H#define C379_H#include<iostream>#include<string>#include<vector>#include<algorithm>using namespace std;bool cmp(const int &a, const int &b){ string astr = to_string(a), bstr = to_string(b); int alen = astr.size(), blen = bstr.size(); if (alen<blen) { for (int i = 0; i < alen; ++i) { if (astr[i] < bstr[i]) { return true; break; } else if (astr[i] == bstr[i]) { if (i == astr.size() - 1) { string s1 = astr + bstr; string s2 = bstr + astr; for (int j = i + 1; j < s1.size(); ++j) { if (s1[j] < s2[j]) { return true; break; } else if (s1[j] == s2[j]) ; else { return false; break; } } } } else { return false; break; } } return true; } else { for (int i = 0; i < blen; ++i) { if (astr[i] < bstr[i]) { return true; break; } else if (astr[i] == bstr[i]) { if (i == bstr.size() - 1) { string s1 = astr + bstr; string s2 = bstr + astr; for (int j = i + 1; j < s1.size(); ++j) { if (s1[j] < s2[j]) { return true; break; } else if (s1[j] == s2[j]) ; else { return false; break; } } } } else { return false; break; } } return false; }}class Solution {public: /* * @param nums: n non-negative integer array * @return: A string */ string minNumber(vector<int> nums) { // write your code here if (nums.empty()) return NULL; sort(nums.begin(), nums.end(), cmp); string str; for (int i = 0; i < nums.size(); ++i) { if (nums[i]!=0) str += to_string(nums[i]); if (i == nums.size() - 1 && str.empty()) str = "0"; } return str; }};#endif
阅读全文
0 0
- lintcode-将数组重新排序以构造最小值
- Lintcode 将数组重新排序以构造最小值
- lintcode[379]将数组重新排序以构造最小值
- lintcode(379)将数组重新排序以构造最小值
- [LintCode]379.将数组重新排序以构造最小值
- LintCode:将数组重新排序以构造最小值
- LINTCODE——将数组重新排序以构造最小值
- 将数组重新排序以构造最小值-LintCode
- 379.Reorder array to construct the minimum number-将数组重新排序以构造最小值(中等题)
- LintCode-寻找旋转排序数组中的最小值
- LintCode 寻找旋转排序数组中的最小值
- LintCode-寻找旋转排序数组中的最小值
- lintcode 寻找旋转排序数组中的最小值
- lintcode,寻找旋转排序数组中的最小值
- lintcode,寻找旋转排序数组中的最小值
- LintCode : 寻找旋转排序数组中的最小值
- lintcode--寻找旋转排序数组中的最小值
- 寻找旋转排序数组中的最小值-LintCode
- 计提与预提的区别?
- 日历备忘录
- [python]python a[::-1]
- mysql 连接错误
- Python-Day03-函数
- 将数组重新排序以构造最小值-LintCode
- Android 随笔(1)
- Dynamics CRM webresource中的html页面url加参数后浏览报500错的解决方法
- Html学习笔记6:表单
- Ubuntu 16.04安装Docker
- 中山大学算法课程题目详解(第四周)
- Android启动相机拍照、相册选取图片,裁剪图片
- c3P0结合DBUtils操作数据库
- 使用ArrayList集合,对其添加10个不同的元素,并使用Iterator遍历该集合