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

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值