查看: 1006| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[高频题] 关于Collection.sort() | LeetCode 987 | 纵向扫树

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
附上下面代码:

我看到 locations的实现,implement了comparable,然后override了CompareTo。

至于原因,我想因为是要给Collection.sort()来用。

问题是,Collection.sort() ,sort的对象一定需要CompareTo接口吗?



/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {

        List<Location> locations;

        public List<List<Integer>> verticalTraversal(TreeNode root) {

            locations = new ArrayList(); /** Each location is a node's x position, y position, and value */

            dfs(root, 0, 0); /* Add all nodes to locations*/

            Collections.sort(locations);

            List<List<Integer>> ans = new ArrayList(); /* final answer container */
            
            ans.add(new ArrayList<Integer>());

            int prev = locations.get(0).x;   /* x is x-axis */

            for (Location loc: locations) {
                // If the x value changed, it's part of a new report.
                if (loc.x != prev) {
                    prev = loc.x;
                    ans.add(new ArrayList<Integer>());
                }

                // We always add the node's value to the latest report.
                ans.get(ans.size() - 1).add(loc.val);
            }

            return ans;
        }

        /** DFS **/
        public void dfs(TreeNode node, int x, int y) {

            if (node != null) {

                /** 加入locations **/
                locations.add(new Location(x, y, node.val));


                dfs(node.left, x-1, y+1);

                dfs(node.right, x+1, y+1);
            }
        }
   

   class Location implements Comparable<Location>{

        int x, y, val;

        Location(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }

        @Override
        public int compareTo(Location that) {

            if (this.x != that.x)
                return Integer.compare(this.x, that.x);
            else if (this.y != that.y)
                return Integer.compare(this.y, that.y);
            else
                return Integer.compare(this.val, that.val);
        }
   
   
   }
}

上一篇:求助一道array的题,lc没找到一样的
下一篇:70天700题,开始吧
无效楼层,该帖已经被删除
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表