179.Largest Number

来源:互联网 发布:js 数组循环 编辑:程序博客网 时间:2024/06/04 19:11

近期开始在LeetCode上开始刷题,第一道题是Largest Number,题目内容如下:

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.


我用C++实现,项链一会儿之后就写出了一段代码,然后,通过在本机上测试简单的用例就通过了,代码如下:

/*179. Largest Number*/#include<iostream>#include<string>#include<vector>#include<algorithm>#include<cstdio>using namespace std;class Solution {public:    string largestNumber(vector<int>& nums) {      vector<string> sortArray;      string result;      char temp[256];      int index = 0, length = 0;      for( vector<int>::iterator it = nums.begin(); it != nums.end(); it++ )      {        sprintf( temp, "%d", *it );        sortArray.push_back(temp);      }      sort(sortArray.begin() , sortArray.end(), sortByWay );      for( index = sortArray.size()-1; index >= 0; index-- )      {        //cout<< sortArray[ index ]<<endl;        result.append( sortArray[ index ] );      }      return result;    }    static bool sortByWay( const string& num1, const string& num2 )    {      return num1 < num2;    }};


然后将代码提交到LeetCode官网上,却出现了如下的结果:


仔细想一下,针对这个用例,我设计算法的时候的确没有想到,所以又重新实现了该问题的解。根据多次提交根据时测试用例的结果进行修改,终于通过了,最后的结果如图:



代码如下:

class Solution {public:    string largestNumber(vector<int>& nums) {      vector<string> sortArray;      string result;      char temp[256];      int index = 0, flag = 1;      for( vector<int>::iterator it = nums.begin(); it != nums.end(); it++ )      {        if( *it != 0 ) flag = 0;        sprintf( temp, "%d", *it );        sortArray.push_back(temp);      }      if( flag )      {        result.append("0");        return result;      }      sort(sortArray.begin() , sortArray.end(), sortByWay );      for( index = sortArray.size()-1; index >= 0; index-- )        //cout<< sortArray[ index ]<<endl;        result.append( sortArray[ index ] );      return result;    }    static bool sortByWay( const string& num1, const string& num2 )    {      string temp1( num1 );      string temp2( num2 );      temp1.append( num2 );      temp2.append( num1 );      return temp1 < temp2;    }};



0 0
原创粉丝点击