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 <= nums[i] <= 10^9 0<=nums[i]<=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;
}
相关推荐
lifallen9 分钟前
Paimon vs. HBase:全链路开销对比
java·大数据·数据结构·数据库·算法·flink·hbase
liujing102329291 小时前
Day04_刷题niuke20250703
java·开发语言·算法
2401_881244402 小时前
Treap树
数据结构·算法
乌萨奇也要立志学C++2 小时前
二叉树OJ题(单值树、相同树、找子树、构建和遍历)
数据结构·算法
网安INF2 小时前
深度学习中的逻辑回归:从原理到Python实现
人工智能·python·深度学习·算法·逻辑回归
wsxqaz2 小时前
浏览器原生控件上传PDF导致hash值不同
算法·pdf·哈希算法
NAGNIP2 小时前
Transformer注意力机制——MHA&MQA&GQA
人工智能·算法
摘星编程2 小时前
多模态AI Agent技术栈解析:视觉-语言-决策融合的算法原理与实践
人工智能·算法·多模态ai·视觉语言融合·ai决策算法
NAGNIP2 小时前
一文搞懂KV-Cache
人工智能·算法
CoovallyAIHub2 小时前
RTMPose:重新定义多人姿态估计的“实时”标准!
深度学习·算法·计算机视觉