(google面试题)找出无序数组中连接和最大排序

来源:互联网 发布:信息和数据的关系是 编辑:程序博客网 时间:2024/05/17 08:20

Problem:Given an integer array, sort the integer array such that the concatenated integer of the result array is max.Example: [4, 94, 9, 14, 1] will be sorted to [9,94,4,14,1] where the result integer is 9944141

Solution: This is an obvious sorting problem that is expected to be done in O(nlogn). The challenge is, how to compare two integers such as 9 and 95, 95 and 953, 95 and 957….

The most intuitive way is to compare two integers from their first digit to the last, and also consider the cases that they have different length. Therefore, many bounder conditions need to be consider,bla..bla..bla...

However, there is an incredible easy way to do the sorting, we can just combine two integers in different orders and see which one is larger. For example, there are only two possible combinations for a pair of integers 9 and 94. Those are, the 994 and the 949, since 994 > 949, they should present in the order that 9 > 94. Another example is 95 and 952, since 95952 > 95295, therefore, 95 goes before 952…

As one can see from below code, the comparison can be done in one line, and you do not need to consider any bounder conditions. However, there is a trick. Since we combine two integers, we may suffer the stack overflow problem, therefore, once they are combined, we need to present them in double format.(int表达的范围小只能用double)

自己使用c++的实现,虽然有点恶心,但是不想使用atof函数,所以使用了stringstream的来实现string和number的互转。

bool compare(int value1, int value2){    stringstream ss;     string str1,str2;    ss << value1;    ss >> str1;    ss.clear();    ss << value2;    ss >> str2;    ss.clear();    double d1,d2;    ss << (str1+str2) << " " << (str2+str1);    ss >> d1 >> d2;     return d1 > d2; }int main ( int argc, char *argv[] ){    int array[] = {4, 94, 9, 14, 1};     vector<int> int_v(array, array+5);       cout << "Before sort:" << endl;    vector<int>::iterator it = int_v.begin();    for (; it != int_v.end(); it++)    {           cout << *it;    }       cout << endl;    sort(int_v.begin(), int_v.end(), compare);    cout << "After sort:" << endl;    it = int_v.begin();    for (; it != int_v.end(); it++)    {           cout << *it;    }    cout << endl;    return 0;}



原创粉丝点击