Leetcode刷题(第341题)——扁平化嵌套列表

x33g5p2x  于2022-03-31 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(380)

一、题目

二、示例

  1. 输入:nestedList = [[1,1],2,[1,1]]
  2. 输出:[1,1,2,1,1]
  3. 解释:通过重复调用 next 直到 hasNext 返回 falsenext 返回的元素的顺序应该是: [1,1,2,1,1]。
  1. 输入:nestedList = [1,[4,[6]]]
  2. 输出:[1,4,6]
  3. 解释:通过重复调用 next 直到 hasNext 返回 falsenext 返回的元素的顺序应该是: [1,4,6]。

三、思路
这里他给了一些方法,我们可以直接进行使用,比如说:isInteger(),getInteger(),getList()。然后我们在代码中就可以使用这些方法了。比较类似于数组的扁平化。
四、代码展示

  1. /**
  2. * // This is the interface that allows for creating nested lists.
  3. * // You should not implement it, or speculate about its implementation
  4. * function NestedInteger() {
  5. *
  6. * Return true if this NestedInteger holds a single integer, rather than a nested list.
  7. * @return {boolean}
  8. * this.isInteger = function() {
  9. * ...
  10. * };
  11. *
  12. * Return the single integer that this NestedInteger holds, if it holds a single integer
  13. * Return null if this NestedInteger holds a nested list
  14. * @return {integer}
  15. * this.getInteger = function() {
  16. * ...
  17. * };
  18. *
  19. * Return the nested list that this NestedInteger holds, if it holds a nested list
  20. * Return null if this NestedInteger holds a single integer
  21. * @return {NestedInteger[]}
  22. * this.getList = function() {
  23. * ...
  24. * };
  25. * };
  26. */
  27. /**
  28. * @constructor
  29. * @param {NestedInteger[]} nestedList
  30. */
  31. var NestedIterator = function (nestedList) {
  32. this.vals = []
  33. const rec = (nest) => {
  34. for (let item of nest) {
  35. if (item.isInteger()) {
  36. this.vals.push(item.getInteger())
  37. } else {
  38. rec(item.getList())
  39. }
  40. }
  41. }
  42. rec(nestedList)
  43. };
  44. /**
  45. * @this NestedIterator
  46. * @returns {boolean}
  47. */
  48. NestedIterator.prototype.hasNext = function () {
  49. return this.vals.length > 0
  50. };
  51. /**
  52. * @this NestedIterator
  53. * @returns {integer}
  54. */
  55. NestedIterator.prototype.next = function () {
  56. return this.vals.shift()
  57. };
  58. /**
  59. * Your NestedIterator will be called like this:
  60. * var i = new NestedIterator(nestedList), a = [];
  61. * while (i.hasNext()) a.push(i.next());
  62. */

五、总结

相关文章