【题意】按照指定规则给mp3歌曲排序,输出前50个歌曲名。
【算法】:
1.建立歌名字符串(不包含“.mp3”)数组
2.排序
3.取出前50个,加上后缀名.mp3
【Java代码】来自菜鸟
1 import java.util.*; 2 import java.util.regex.*; 3 import java.text.*; 4 import java.math.*; 5 6 7 public class FoxAndMp3Easy 8 { 9 public String[] playList(int n) 10 { 11 TreeSet<String> set = new TreeSet<String>(); 12 int i; 13 14 for(i=1;i<=n;i++){ 15 set.add(""+i); 16 } 17 18 String[] r = new String[Math.min(50,n)]; 19 Iterator<String> it = set.iterator(); 20 21 for(i=0;i<Math.min(50, n);i++){ 22 r[i]=it.next()+".mp3"; 23 } 24 25 return r; 26 } 27 28 29 } 30 //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
【Java代码】来自大神
import java.util.*; public class FoxAndMp3Easy { public String[] playList(int n) { List<String> mp3List = new ArrayList<String>(); for(int i=1;i<=n;i++) { mp3List.add(String.valueOf(i)); } Collections.sort(mp3List, new Comparator<String>() { public int compare(String a, String b) { return a.compareTo(b); } }); int len = mp3List.size(); if(len>50) len = 50; String[] result = new String[len]; for(int i=0;i<len;i++) { result[i] = mp3List.get(i)+".mp3"; } return result; } }
【C++代码】来自大神
【分析】大神直接把".mp3"加进去比较,因为'.'是比'0'到'9'都小,'.'是46,'0'是48。
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <climits> using namespace std; #define INF INT_MAX #define EPS 1e- #define abs(a) ((a)<0?-(a):(a)) #define FOR(i,a,b) for(int i=a;i<b;i++) #define REP(i,n) FOR(i,0,n) #define MP make_pair #define FR first #define SE second #define PB(X) push_back(X) #define tri(a,b,c) MP(a,MP(b,c)) #define IND(arr,ind) (lower_bound(all(arr),ind)-arr.begin()) class FoxAndMp3Easy { public: vector <string> playList(int n) { vector <string> ret; for(int i=1;i<=n;i++){ stringstream ss; ss<<i; ret.push_back(ss.str()+".mp3"); } sort(ret.begin(),ret.end()); if(ret.size()>50){ ret.erase(ret.begin()+50,ret.end()); } return ret; } }; //Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
【总结】:题还是比较简单的。
附上ASCII码表http://www.96yx.com/tool/ASC2.htm