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;
}
相关推荐
福尔摩斯张2 小时前
Linux进程间通信(IPC)机制深度解析与实践指南
linux·运维·服务器·数据结构·c++·算法
你好~每一天2 小时前
未来3年,最值得拿下的5个AI证书!
数据结构·人工智能·算法·sqlite·hbase·散列表·模拟退火算法
杰克尼2 小时前
3. 分巧克力
java·数据结构·算法
zore_c2 小时前
【C语言】带你层层深入指针——指针详解2
c语言·开发语言·c++·经验分享·笔记
zmzb01033 小时前
C++课后习题训练记录Day39
数据结构·c++·算法
Ayanami_Reii3 小时前
进阶数学算法-取石子游戏(ZJOI2009)
数学·算法·游戏·动态规划·区间dp·博弈论
一只小小汤圆3 小时前
已知圆弧的起点、终点、凸度 求圆弧的圆心
算法
丸码3 小时前
Java HashMap深度解析
算法·哈希算法·散列表
算法与编程之美4 小时前
Java数组动态扩容
java·开发语言·python·算法
2301_764441334 小时前
三维建筑非法入侵情景推演
python·学习·算法