leetcode 506. Relative Ranks
Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1] Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". For the left two athletes, you just need to output their relative ranks according to their scores.Note:
N is a positive integer and won't exceed 10,000.All the scores of athletes are guaranteed to be unique.AC:
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ char** findRelativeRanks(int* nums, int numsSize, int* returnSize) { char** result=(char**)malloc(numsSize*sizeof(char*)); int A[10000]; for(int j=0;j<numsSize;j++) { A[j]=j; } for(int i=0;i<numsSize-1;i++) { for(int j=i+1;j<numsSize;j++) { if(nums[i]<nums[j]) { int k=nums[i]; nums[i]=nums[j]; nums[j]=k; k=A[i]; A[i]=A[j]; A[j]=k; } } } for(int i=0;i<numsSize;i++) { result[A[i]]=(char*)malloc(13*sizeof(char)); if(i>=3) { char buf[32]; sprintf(buf,"%d",i+1); strcpy(result[A[i]],buf); }else if(i==0) { strcpy(result[A[0]],"Gold Medal"); } else if(i==1) { strcpy(result[A[1]],"Silver Medal"); } else if(i==2) { strcpy(result[A[2]],"Bronze Medal"); } } *returnSize=numsSize; return result; } tips: C 数字转字符串 sprintf(char buf[],"%d", num); 字符串转数字 long int strtol(const char *nptr,char **endptr,int base); strtol函数说明 编辑 参数base范围从2至36,或0。参数base代表采用的进制方式,如base值为10则采用10进制,若base值为16则采用16进制等。当base值为0时则是采用10进制做转换,但遇到如’0x’前置字符则会使用16进制做转换、遇到’0’前置字符而不是’0x’的时候会使用8进制做转换。 一开始strtol()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,再遇到非数字或字符串结束时('\0')结束转换,并将结果返回。若参数endptr不为NULL,则会将遇到不合条件而终止的nptr中的字符 指针由endptr返回;若参数endptr为NULL,则会不返回非法字符串。