栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Leetcode Java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode Java

List
  • 1200. 最小绝对差
  • ★1436. 旅行终点站
  • 2011. 执行操作后的变量值

1200. 最小绝对差

Leetcode
知识点: Arrays.sort(), List, add, clear()

class Solution {
    public List> minimumAbsDifference(int[] arr) {
        Arrays.sort(arr);
        List> lists = new ArrayList<>();
        // List list = new ArrayList<>();
        int n = arr.length, min = Integer.MAX_VALUE, x;
        for(int i = 1; i < n; i++){            
            x = arr[i] - arr[i-1];
            if (x <= min) {
                if (x < min)  lists.clear();
                // list.clear();
                // list.add(arr[i-1]);
                // list.add(arr[i]);
                // lists.add(new ArrayList<>(list));
                List list = List.of(arr[i-1], arr[i]);
                lists.add(list);
                min = x;
            }
        }
        return lists;
    }
}
★1436. 旅行终点站

Leetcode
知识点: List, add, get, contains。

class Solution {
    public String destCity(List> paths) {
        List start = new ArrayList<>();
        List end = new ArrayList<>();
        for (List path:paths){
            start.add(path.get(0));
            end.add(path.get(1));
        }
        for (String s:end){
            if (!start.contains(s)) return s;
        }
        return "";
    }
}
// 使用 set
class Solution {
    public String destCity(List> paths) {
        Set citiesA = new HashSet();
        for (List path : paths) {
            citiesA.add(path.get(0));
        }
        for (List path : paths) {
            if (!citiesA.contains(path.get(1))) {
                return path.get(1);
            }
        }
        return "";
    }
}
2011. 执行操作后的变量值

Leetcode
知识点:

class Solution {
    public int finalValueAfterOperations(String[] operations) {
        int x = 0;
        for (String s: operations){
            // x += s.contains("+") ? 1:-1;
            x += (s.equals("X++") || s.equals("++X")) ? 1:-1;
            // 使用 == 和 equals() 比较字符串。
            // String 中 == 比较引用地址是否相同,
            // equals() 比较字符串的内容是否相同。
            // x += (s == "X++" || s == "++X") ? 1:-1;
        }
        return x;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/643665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号