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;
}
相关推荐
GQH10002 分钟前
运算符、分支语句
linux·c语言
小柯J桑_22 分钟前
史上最牛排序集合,带你认清所有排序算法!(必看系列)~
数据结构·算法·排序算法
无限大.1 小时前
c语言200例 64
c语言·数据结构·算法
luluvx1 小时前
LeetCode[中等] 78.子集
算法·leetcode·职场和发展
sp_fyf_20241 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-09-26
人工智能·深度学习·神经网络·算法·语言模型·自然语言处理·数据挖掘
DdddJMs__1351 小时前
C语言 | Leetcode C语言题解之第433题最小基因变化
c语言·leetcode·题解
大二转专业1 小时前
408算法题leetcode--第16天
考研·算法·leetcode
xjjeffery2 小时前
网络基础概念和 socket 编程
linux·c语言·网络·后端
Liu_Junwei2 小时前
如何解决哈希冲突?
数据结构·算法·哈希算法
席万里2 小时前
1605. 给定行和列的和求可行矩阵
数据结构·线性代数·算法·leetcode·矩阵·golang