LeetCode //C - 386. Lexicographical Numbers

386. Lexicographical Numbers

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.

You must write an algorithm that runs in O(n) time and uses O(1) extra space.

Example 1:

Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]

Example 2:

Input: n = 2
Output: [1,2]

Constraints:
  • 1 < = n < = 5 ∗ 1 0 4 1 <= n <= 5 * 10^4 1<=n<=5∗104

From: LeetCode

Link: 386. Lexicographical Numbers


Solution:

Ideas:
  • Handling integers: If s doesn't start with a [, it's a single integer, so we parse it using atoi and return a NestedInteger containing that integer.
  • Handling lists: We traverse through the string character by character.
    • When encountering [, we initialize a new NestedInteger and push the current one onto a stack if necessary.
    • When encountering ], we pop from the stack and add the current NestedInteger to the parent.
    • When encountering digits (or - for negative numbers), we parse the number and add it to the current list.
  • Memory management: We use a stack to keep track of nested structures, and
Code:
c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void dfs(int current, int n, int* result, int* index) {
    // Add the current number to the result array
    result[(*index)++] = current;

    // Try to append digits (0-9) to the current number
    for (int i = 0; i <= 9; i++) {
        int next = current * 10 + i;
        if (next > n) {
            break; // Stop if the number exceeds n
        }
        dfs(next, n, result, index);
    }
}

int* lexicalOrder(int n, int* returnSize) {
    // Allocate memory for the result array
    int* result = (int*)malloc(n * sizeof(int));
    int index = 0;

    // Perform DFS starting from 1 to 9
    for (int i = 1; i <= 9; i++) {
        if (i > n) {
            break;
        }
        dfs(i, n, result, &index);
    }

    // Set the return size
    *returnSize = n;
    return result;
}
相关推荐
带多刺的玫瑰1 小时前
Leecode刷题C语言之统计不是特殊数字的数字数量
java·c语言·算法
爱敲代码的憨仔1 小时前
《线性代数的本质》
线性代数·算法·决策树
yigan_Eins2 小时前
【数论】莫比乌斯函数及其反演
c++·经验分享·算法
阿史大杯茶2 小时前
AtCoder Beginner Contest 381(ABCDEF 题)视频讲解
数据结构·c++·算法
陌小呆^O^2 小时前
Cmakelist.txt之win-c-udp-server
c语言·开发语言·udp
დ旧言~2 小时前
【高阶数据结构】图论
算法·深度优先·广度优先·宽度优先·推荐算法
时光の尘2 小时前
C语言菜鸟入门·关键字·float以及double的用法
运维·服务器·c语言·开发语言·stm32·单片机·c
张彦峰ZYF2 小时前
投资策略规划最优决策分析
分布式·算法·金融
-一杯为品-3 小时前
【51单片机】程序实验5&6.独立按键-矩阵按键
c语言·笔记·学习·51单片机·硬件工程
The_Ticker3 小时前
CFD平台如何接入实时行情源
java·大数据·数据库·人工智能·算法·区块链·软件工程