LeetCode //C - 341. Flatten Nested List Iterator

341. Flatten Nested List Iterator

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

Implement the NestedIterator class:

  • NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList.
  • int next() Returns the next integer in the nested list.
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

Your code will be tested with the following pseudocode:

c 复制代码
initialize iterator with nestedList
res = []
while iterator.hasNext()
    append iterator.next() to the end of res
return res

If res matches the expected flattened list, then your code will be judged as correct.

Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:

Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

Constraints:
  • 1 <= nestedList.length <= 500
  • The values of the integers in the nested list is in the range [ − 1 0 6 , 1 0 6 ] [-10^6, 10^6] [−106,106].

From: LeetCode

Link: 341. Flatten Nested List Iterator


Solution:

Ideas:
  1. resizeFlattenedList Function: This function checks if the flattenedList array needs more space (i.e., when size >= capacity). If it does, the capacity is doubled, and the array is reallocated to the new size.

  2. Dynamic Array Allocation: The flattenedList array starts with an initial capacity of 100. Whenever the array needs more space, it doubles its capacity. This ensures that the array can grow as needed without causing a buffer overflow.

  3. Flattening Logic: The flatten function remains responsible for traversing the nested list structure. It now calls resizeFlattenedList before adding each integer to ensure there's enough space in the flattenedList array.

Code:
c 复制代码
/**
 * *********************************************************************
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * *********************************************************************
 *
 * // Return true if this NestedInteger holds a single integer, rather than a nested list.
 * bool NestedIntegerIsInteger(struct NestedInteger *);
 *
 * // Return the single integer that this NestedInteger holds, if it holds a single integer
 * // The result is undefined if this NestedInteger holds a nested list
 * int NestedIntegerGetInteger(struct NestedInteger *);
 *
 * // Return the nested list that this NestedInteger holds, if it holds a nested list
 * // The result is undefined if this NestedInteger holds a single integer
 * struct NestedInteger **NestedIntegerGetList(struct NestedInteger *);
 *
 * // Return the nested list's size that this NestedInteger holds, if it holds a nested list
 * // The result is undefined if this NestedInteger holds a single integer
 * int NestedIntegerGetListSize(struct NestedInteger *);
 * };
 */
// This structure will hold our iterator state
struct NestedIterator {
    int *flattenedList;  // Array to hold the flattened list
    int size;            // Size of the flattened list
    int capacity;        // Capacity of the flattened list
    int index;           // Current index in the flattened list
};

// Helper function to resize the flattened list array if needed
void resizeFlattenedList(struct NestedIterator *iter) {
    if (iter->size >= iter->capacity) {
        iter->capacity *= 2;  // Double the capacity
        iter->flattenedList = (int *)realloc(iter->flattenedList, iter->capacity * sizeof(int));
    }
}

// Helper function to flatten the nested list recursively
void flatten(struct NestedInteger **nestedList, int nestedListSize, struct NestedIterator *iter) {
    for (int i = 0; i < nestedListSize; i++) {
        if (NestedIntegerIsInteger(nestedList[i])) {
            // If it's an integer, add it to the result array
            resizeFlattenedList(iter);
            iter->flattenedList[iter->size++] = NestedIntegerGetInteger(nestedList[i]);
        } else {
            // If it's a list, recursively flatten it
            struct NestedInteger **subList = NestedIntegerGetList(nestedList[i]);
            int subListSize = NestedIntegerGetListSize(nestedList[i]);
            flatten(subList, subListSize, iter);
        }
    }
}

// Initializes the iterator with the nested list
struct NestedIterator *nestedIterCreate(struct NestedInteger** nestedList, int nestedListSize) {
    // Allocate memory for the iterator
    struct NestedIterator *iter = (struct NestedIterator *)malloc(sizeof(struct NestedIterator));
    iter->capacity = 100;  // Start with an initial capacity
    iter->flattenedList = (int *)malloc(iter->capacity * sizeof(int));
    iter->size = 0;
    iter->index = 0;

    // Flatten the nested list into the flattenedList array
    flatten(nestedList, nestedListSize, iter);
    
    return iter;
}

// Returns true if there are more integers to return
bool nestedIterHasNext(struct NestedIterator *iter) {
    return iter->index < iter->size;
}

// Returns the next integer in the flattened list
int nestedIterNext(struct NestedIterator *iter) {
    return iter->flattenedList[iter->index++];
}

// Deallocates memory previously allocated for the iterator
void nestedIterFree(struct NestedIterator *iter) {
    free(iter->flattenedList);
    free(iter);
}
/**
 * Your NestedIterator will be called like this:
 * struct NestedIterator *i = nestedIterCreate(nestedList, nestedListSize);
 * while (nestedIterHasNext(i)) printf("%d\n", nestedIterNext(i));
 * nestedIterFree(i);
 */
相关推荐
AndrewHZ2 小时前
【图像处理基石】什么是油画感?
图像处理·人工智能·算法·图像压缩·视频处理·超分辨率·去噪算法
.格子衫.2 小时前
015枚举之滑动窗口——算法备赛
数据结构·算法
Despacito0o3 小时前
QMK键盘固件自定义指南 - 打造你的专属键盘体验
c语言·计算机外设·qmk
J先生x3 小时前
【IP101】图像处理进阶:从直方图均衡化到伽马变换,全面掌握图像增强技术
图像处理·人工智能·学习·算法·计算机视觉
爱coding的橙子5 小时前
每日算法刷题 Day3 5.11:leetcode数组2道题,用时1h(有点慢)
算法·leetcode
Dream it possible!9 小时前
LeetCode 热题 100_只出现一次的数字(96_136_简单_C++)(哈希表;哈希集合;排序+遍历;位运算)
c++·leetcode·位运算·哈希表·哈希集合
?abc!10 小时前
缓存(5):常见 缓存数据淘汰算法/缓存清空策略
java·算法·缓存
BioRunYiXue10 小时前
一文了解氨基酸的分类、代谢和应用
人工智能·深度学习·算法·机器学习·分类·数据挖掘·代谢组学
Dddle110 小时前
C++:this指针
java·c语言·开发语言·c++
不見星空11 小时前
2025年第十六届蓝桥杯软件赛省赛C/C++大学A组个人解题
c语言·c++·蓝桥杯