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 小时前
基于野火F407开发板实现电源管理-停止模式
c语言·stm32·单片机·嵌入式硬件·mcu
蒋星熠2 小时前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
小莞尔2 小时前
【51单片机】【protues仿真】基于51单片机宠物投食系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小欣加油2 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
3Cloudream2 小时前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
王璐WL3 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法
空白到白3 小时前
机器学习-聚类
人工智能·算法·机器学习·聚类
小马学嵌入式~3 小时前
嵌入式 SQLite 数据库开发笔记
linux·c语言·数据库·笔记·sql·学习·sqlite
索迪迈科技3 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
zzzsde4 小时前
【数据结构】队列
数据结构·算法