微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java - 在列表中多次添加值

如何解决Java - 在列表中多次添加值

我正在尝试在 1 00:00:01,100 --> 00:00:04,100 This is a test subtitle. 2 00:00:04,100 --> 00:00:06,100 !!!CLEAR!!! 3 00:00:06,100 --> 00:00:08,100 This is another subtitle. 添加一些子列表一次。但问题是,它被多次添加

这是代码

List<List<Integer>>

请帮我解决这个问题。

提前致谢。

P.S:我认为这是一个愚蠢的错误或失误。

解决方法

发生这种情况是因为您一次又一次地添加列表。您需要在结果列表中添加列表,即 res 仅当 res 中不存在对应于该特定级别的列表时。

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if(root == null) return new ArrayList<>(); // you don't need to return null,return empty list.
        
        List<List<Integer>> res = new ArrayList<>();
        Queue<Pair> q = new LinkedList<>();
        
        q.add(new Pair(root,0));
        
        while(!q.isEmpty()) {

          int n = q.size();

          for(int i = 0 ; i  < n ; i++){

            Pair tmp = q.poll();
            int data = tmp.root.val;
            int level = tmp.level;
            
            List<Integer> list;
            // get number of sublists in res
            if(res.size() == level) {
              list = new ArrayList<>();
              list.add(data);
              res.add(list); // You need to add list into res only when there is no list corresponding to that level.
            }
            
            else {
              list = res.get(level);
              // System.out.println("existing list = " + list);
              if(level % 2 == 0) {
                list.add(data);
              }
              else list.add(0,data);
            }

            
            if(tmp.root.left != null) q.add(new Pair(tmp.root.left,level + 1));
            if(tmp.root.right != null) q.add(new Pair(tmp.root.right,level + 1));
          }
        }
        return res;
    }
}
    
class Pair {
  TreeNode root;
  int level;

  Pair(TreeNode root,int level) {
    this.root = root;
    this.level = level;
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。