LeetCode //C - 179. Largest Number

179. Largest Number

Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.

Since the result may be very large, so you need to return a string instead of an integer.

Example 1:

Input: nums = 10,2
Output: "210"

Example 2:

Input: nums = 3,30,34,5,9
Output: "9534330"

Constraints:
  • 1 <= nums.length <= 100
  • 0 < = n u m s i < = 1 0 9 0 <= numsi <= 10^9 0<=numsi<=109

From: LeetCode

Link: 179. Largest Number


Solution:

Ideas:
  1. Convert integers to strings: Since the concatenation of numbers as strings is required, the integers are first converted to strings.

  2. Custom Comparator: A custom comparator function is used to sort these strings. The key idea here is to determine the order of any two strings a and b by comparing the two possible concatenations: a+b and b+a. If a+b is greater than b+a, then a should come before b in the final order, and vice versa.

  3. Sort the strings: Using the custom comparator, the list of strings is sorted in such a way that concatenating them in this order results in the largest possible number.

  4. Concatenate sorted strings: After sorting, the strings are concatenated together to form the final result.

  5. Edge Case Handling: If the largest number is 0, meaning all numbers are zero, the result should simply be "0".

Code:
c 复制代码
int compare(const void *a, const void *b) {
    // Cast the pointers to strings
    const char *str1 = *(const char **)a;
    const char *str2 = *(const char **)b;
    
    // Allocate enough space to hold the two concatenated results
    char option1[22];
    char option2[22];
    
    // Concatenate str1+str2 and str2+str1
    sprintf(option1, "%s%s", str1, str2);
    sprintf(option2, "%s%s", str2, str1);
    
    // Return the comparison result in descending order
    return strcmp(option2, option1);
}

char* largestNumber(int* nums, int numsSize) {
    if (numsSize == 0) return "";

    // Convert numbers to strings
    char **numsStr = (char **)malloc(numsSize * sizeof(char *));
    for (int i = 0; i < numsSize; ++i) {
        numsStr[i] = (char *)malloc(12 * sizeof(char)); // Enough for an integer with max 10 digits and a null terminator
        sprintf(numsStr[i], "%d", nums[i]);
    }

    // Sort the array with custom comparator
    qsort(numsStr, numsSize, sizeof(char *), compare);

    // If the highest number is "0", the entire number is "0"
    if (strcmp(numsStr[0], "0") == 0) {
        // Free allocated memory
        for (int i = 0; i < numsSize; ++i) {
            free(numsStr[i]);
        }
        free(numsStr);
        return "0";
    }

    // Calculate total length for the resulting string
    int totalLength = 0;
    for (int i = 0; i < numsSize; ++i) {
        totalLength += strlen(numsStr[i]);
    }

    // Allocate space for the result string
    char *result = (char *)malloc((totalLength + 1) * sizeof(char));
    result[0] = '\0'; // Initialize to an empty string

    // Concatenate all strings
    for (int i = 0; i < numsSize; ++i) {
        strcat(result, numsStr[i]);
        free(numsStr[i]); // Free the individual string after use
    }

    free(numsStr); // Free the array of string pointers

    return result;
}
相关推荐
玖玥拾12 分钟前
C/C++ 基础笔记(二)
c语言·c++
Zldaisy3d20 分钟前
全球唯一仿真驱动自适应扫描路径新版本发布,金属3D打印工艺开发进入算法时代
算法·3d
小江的记录本24 分钟前
【JVM虚拟机】类加载机制:类加载全流程:加载→验证→准备→解析→初始化(附《思维导图》+《面试高频考点清单》)
java·jvm·spring boot·算法·安全·spring·面试
故事和你911 小时前
洛谷-【动态规划2】线性状态动态规划4
开发语言·数据结构·c++·算法·动态规划·图论
不吃土豆的马铃薯1 小时前
Socket 网络编程实战教程
linux·服务器·开发语言·网络·c++·算法
longxiangam2 小时前
esp-idf dsi 屏幕的驱动实现原理—— 关于零拷贝和 DMA 永续刷新
c语言·单片机·嵌入式硬件
weixin_468466852 小时前
图像滤波算法新手实战指南
图像处理·人工智能·算法·计算机视觉·ai·机器视觉·滤波
Ulyanov2 小时前
深入QML-Python通信 构建响应式交互界面的桥梁设计:QML+PySide6现代开发入门(五)
开发语言·python·算法·交互·qml·系统仿真
重生之我是Java开发战士2 小时前
【贪心算法】加油站,单调递增的数字,坏了的计算器,合并区间,用最少数量的箭引爆气球
算法·贪心算法
zz34572981132 小时前
函数:python与c语言
c语言·开发语言·python