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;
}
相关推荐
凌辰揽月34 分钟前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
lifallen40 分钟前
深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
java·开发语言·数据结构·算法·排序算法
jingfeng51441 分钟前
数据结构排序
数据结构·算法·排序算法
whoarethenext1 小时前
使用 C/C++的OpenCV 实时播放火柴人爱心舞蹈动画
c语言·c++·opencv
能工智人小辰1 小时前
Codeforces Round 509 (Div. 2) C. Coffee Break
c语言·c++·算法
kingmax542120081 小时前
CCF GESP202503 Grade4-B4263 [GESP202503 四级] 荒地开垦
数据结构·算法
岁忧1 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode
eachin_z2 小时前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
闻缺陷则喜何志丹2 小时前
【强连通分量 缩点 拓扑排序】P3387 【模板】缩点|普及+
c++·算法·拓扑排序·洛谷·强连通分量·缩点
机器学习之心3 小时前
机器学习用于算法交易(Matlab实现)
算法·机器学习·matlab