- 1200. 最小绝对差
- ★1436. 旅行终点站
- 2011. 执行操作后的变量值
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;
}
}



