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;
}
相关推荐
学不动CV了2 小时前
ARM单片机启动流程(二)(详细解析)
c语言·arm开发·stm32·单片机·51单片机
大千AI助手2 小时前
DTW模版匹配:弹性对齐的时间序列相似度度量算法
人工智能·算法·机器学习·数据挖掘·模版匹配·dtw模版匹配
YuTaoShao4 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
生态遥感监测笔记4 小时前
GEE利用已有土地利用数据选取样本点并进行分类
人工智能·算法·机器学习·分类·数据挖掘
猫猫的小茶馆4 小时前
【STM32】通用定时器基本原理
c语言·stm32·单片机·嵌入式硬件·mcu·51单片机
Tony沈哲5 小时前
macOS 上为 Compose Desktop 构建跨架构图像处理 dylib:OpenCV + libraw + libheif 实践指南
opencv·算法
刘海东刘海东5 小时前
结构型智能科技的关键可行性——信息型智能向结构型智能的转变(修改提纲)
人工智能·算法·机器学习
pumpkin845146 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
挺菜的6 小时前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法