题解:把数组排成最小的数

题目摘自《剑指Offer》

题目:

输入一个正整数数组,将它们连接起来排成一个数,输出能排出的所有数字中最小的一个。例如输入数组{32,  321},则输出这两个能排成的最小数字32132

思路:

1. 对数组进行排序,理应处在高位的数排序后应位于数组的前端,处在低位的数排序后位于数组的后端。设数组中两个数为a和b,若ab < ba,则在排序时a应排在b前,如a=10, b = 1,尽管a > b,但ab = 101 < ba = 110,所以a应排在b前。以此为规则,对数组中的所有数进行排序。证明ab < ba, bc < cb,则 ac < ca的过程略,但此传递性是此算法正确的核心。


2. 这里的陷阱是,若a和b均为很大的数,则连接后ab可能超出int的表示范围,解决方法是将整数的连接用字符串表示。


题解:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;


class Solution {
public:
		
	void SmallestCatenation( vector<int> numArray, int max )
	{
		maxIntegerLength = max;
		if(!numArray.size() || maxIntegerLength <= 0)
			return;
		sort(numArray.begin(), numArray.end(), myFunction);

		for(auto iter: numArray)
		{
			cout << iter;
		}
		cout << endl;
		return;
	}

	static bool myFunction(int number1, int number2)
	{
		char* temp1 = new char[maxIntegerLength + 1];
		char* temp2 = new char[maxIntegerLength + 1];
		sprintf(temp1, "%d", number1);
		sprintf(temp2, "%d", number2);

		string str1 = temp1;
		string str2 = temp2;

		if(str1.append(str2).compare(str2.append(str1)) < 0)
			return true;
		else
			return false;

	}

	static int maxIntegerLength;
};

int Solution::maxIntegerLength = 0;

int main(int argc, const char* argv[])
{
	int input[] = {3, 32, 321};
	
	vector<int> inputArray(input, input+sizeof(input)/sizeof(int));
	Solution s;
	
	s.SmallestCatenation(inputArray, 3);
	return 0;
}


你可能感兴趣的:(Algorithm)