API入门
# 写给读者
各个语言都会有些常见的但写起来比较操蛋的内容,本文做一个集中记录,方便读者笔试前统一复习
另外,我推荐各位读者掌握python
,java
,c++
这三种语言的基础语法。可能你未来主要从事Java行业,但我也推荐你学会这三种语言。
就拿最实际的来说吧,一般大公司都会有一轮笔试,笔试时间珍贵,你要在最短的时间内把题目做出来。这时候python
简洁的语法优势就会显示出来,你可以在更短的时间写出代码,为你做后续题目节省时间。
BUT,python的运行效率是低于c++
的,因此对于某些卡时间复杂度的题目,可以选择c++
暴力破解。
那么啥时候推荐使用java
呢?在我看来,遇到一些字符串处理的题目,Java相较于python还是占优的。一方面java没有c++那么复杂,另一方面在字符串API上除了切片功能,大部分情况下我个人认为java比python好用,比如python是无法做出'a' + 1
这样的操作,这就显得格外蛋疼了。
# Java
# 1.字符串
str.length(); // 字符串(有括号)
nums.length; // 数组(无括号)
1
2
2
# 字符串判等
// 字符串判等,不能==
s1.equals(s2);
1
2
2
# 字符串判空
isEmpty() <==> length()=0
1
# 字符串遍历
char s = str.charAt(index); // 访问某个字符
str.setCharAt(int index, char ch);//将指定索引处的字符替换为ch
// 字符串转数组
char[] chars = str.toCharArray();
for(s1 : s.toCharArray()){} // 字符串遍历
1
2
3
4
5
6
2
3
4
5
6
# 字符串检索
int s =str.indexOf("文艺倾年"); // 检索字符串
1
# 字符串提取
s = str.substring(0,1); // (,] 范围
1
# 字符串反转
str = new StringBuilder(str).reverse().toString();
1
# 字符串转化
str.toUpperCase(); // 大写
str.toLowerCase(); // 小写
int a = Integer.parseInt(str); // 字符串→数字
String s = String.valueOf(value); // Other→字符串
// valueOf()传入null返回null,而toString()报空指针异常
// copyValueOf()往往处理字符数组用
copyValueOf(char[] data): 返回指定数组中表示该字符序列的字符串。
copyValueOf(char[] data, int start, int count):返回指定数组中指定片段的字符串。
start:开始下标 count:长度
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 字符串拆分
String[] strs = str.split(" "); // 字符串分割
str.trim(); // 去除头尾空格
1
2
3
2
3
# 字符串比较
str1.compareTo(str2); // 字典序比较 '12'.'21'<0
1
# 字符串替换
str.replace("文艺倾年","小航"); // 字符串替换
1
# 2.数组
Arrays.fill(nums, 0); // 填充数组为0
Arrays.sort(nums); // 升序
// 数组拷贝
numsA.clone(numsB); // 把numsB的值拷贝给numsA
Arrays.copyOf(int[] a, int length);//从a数组的第一个元素开始复制,复制length个元素。
Arrays.copyOfRange(int[] a, int begin, int to);//从a数组begin开始复制,到to-1位置结束。
// 转数组
list.stream().filter(integer -> inter != null).mapToInt(i -> i).toArray();
set.stream().filter(integer -> inter != null).mapToInt(i -> i).toArray();
int[][] res = list.toArray(new int[0][0]);
Integer[] nums = list.toArray(Integer[]::new);
// 数组转list
List<Integer> list = new ArrayList<>(Arrays.asList(arrays));
List<Integer> list = Arrays.stream(arrays).collect(Collectors.toList());
List<Integer> list = CollectionUtils.arrayToList(arrays);
// 数组求和
for (int element : array) sum += element;
int sum = Arrays.stream(arrays).sum();
int sum = IntStream.of(array).sum();
// 数组求最值
int maxNum = Arrays.stream(arrays).max().getAsInt();
int maxNum = Collections.max(Arrays.asList(arrays));
int maxNum = Arrays.stream(arrays).min().getAsInt();
int maxNum = Collections.min(Arrays.asList(arrays));
Collections.fill(list,0); // 填充数组为0
// 增删查改
list.add(1);
list.add(3,4); // 将4插入到第三个位置
list.remove(3); // 删除下标为3的
list.set(1, 2); // 将1下标的元素改为2
list.get(1);
Collections.sort(list); // 排序
Collections.max(list); // 最大值
Collections.min(list);
Collections.shuffle(list); //list洗牌
Collections.reverse(list); // 翻转
list.toArray() // list变数组
list.isEmpty() //list是否为空
list.clear(); //移除所有元素。
list.size();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 3.Map
# HashMap
map.put(key, value); // 插入
// 查找
if(map.containsKey(k));
if(map.containsvalue(v));
int value = map.get(k); // 取值
map.clear(); // 清空
map.remove(key); // 移除指定键的映射关系
// 遍历
Iterator<Integer> it = map.keySet().iterator();
while(it.hasNext()){
Integer key=it.next();
Integer value=map.get(key);
}
// 提取其中所有key
for(Integer key : map.keySet()){
...
}
// 提取所有value
for(String value : map.values()){
...
}
// 计数统计
// 如果map存在num,原来的value + 1
// 如果map不存在num,设置value = 1
map.put(num, map.getOrDefault(num, 0) + 1);
// 合并
map.merge(num, 1, Integer::sum);
map.put(num, map.getOrDefault(num, 0) + 1);
// 合并两者
map.merge(num, 1, (old, new) -> old + new)
// 保留旧值
map.merge(num, 1, (old, new) -> old)
// 覆盖旧值
map.merge(num, 1, (old, new) -> new)
// 删除旧值
map.merge(num, 1, (old, new) -> null)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# TreeMap
TreeMap是基于红黑树实现的,是有序的
tree.firstKey(); // 第一个(最低)键。
tree.lastKey(); // 最后一个(最高)键
1
2
2
# 4.Set
# HashSet
set.add(a); // 插入
set.remove(b); // 删除
set.contains(a); // 查询
set.remove(a); // 移除
set.clear(); // 清除
1
2
3
4
5
2
3
4
5
# TreeSet
tree.first(); //返回第一个元素
tree.last(); //返回最后一个元素
tree.higher(E e) // 返回严格大于给定元素的最小元素,不存在返回null
tree.lower(E e) // 返回严格小于给定元素的最大元素,不存在返回null
1
2
3
4
5
2
3
4
5
# 5.LinkedList
LinkedList<Pet> pets = new LinkedList<Pet>(Pet.arrayList(5));//生成五个Pet对象
// 取第一个
pets.getFirst() // 列表为空返回NoSuchElement-Exception
pets.element() // 列表为空返回NoSuchElement-Exception
pets.peek() // 列表为空返回null
// 移除第一个,并返回列表头
pets.removeFirst() // 列表为空返回NoSuchElement-Exception
pets.remove() // 列表为空返回NoSuchElement-Exception
pets.poll() // 列表为空返回null
pets.addFirst(new Rat()); // 插入头部
// 插入尾部
pets.addLast(new Rat());
pets.add(new Rat());
pets.offer(new Rat());
pets.set(2,new Rat());//将替换为指定的元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 6.PriorityQueue
默认小顶堆
// 默认初始容量为11
PriorityQueue<Integer> Q = new PriorityQueue<>(); // 初始化
add(E e)//将指定的元素插入此优先级队列。
offer(E e) // 将指定元素插入此优先队列
poll() // 获取并移除第一个
remove(Object o) // 移除指定元素
clear()//清空
peek() // 获取第一个元素,及最小或最大元素
contains(Object o) // 如果包含指定元素返回true
iterator()//返回在此队列中的元素上进行迭代的迭代器。
size() // 返回元素个数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 7.自定义比较器
# 数组排序 Arrays.sort()
Arrays.sort(arr, new Comparator<Integer>() { // arr是数组名,<>中是待排序集合所包含的数据类型
public int compare(int a, int b){ // 待排序集合中的元素是什么数据类型,这里的两个函数参数就定义为什么数据类型
return a - b; 升序
// return b - a; 降序
// a - b > 0 交换ab位置,反之不变, 即返回值为正数时,交换数组中正在比较的
//两个元素的位置,返回值为负数时,不交换。
}
})
// lambda表达式,如果不知道怎么写是升序,怎么写是降序,只需要记住 左边在左边,右边在右边,这就是升序。
Arrays.sort(arr, (int a, int b) -> a - b); // 升序
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 集合排序 Collections.sort()
TreeSet<Integer> s = new TreeSet<>(new Comparator<Integer>(){
public int compare(Integer a, Integer b) {
return b - a;
}
});
1
2
3
4
5
2
3
4
5
# 自定义数组对象排序
法一:
//对pair类实现Comparable接口后,直接调用sort函数排序就行了。
static class pair implements Comparable<pair>{
int a, b, w;
pair(int u, int v, int x){
a = u;
b = v;
w = x;
}
public int compareTo(pair p) {
return this.w - p.w;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
法二:
Arrays.sort(s, new Comparator<student>() {
public int compare(student a, student b) { //
return a.age - b.age; // 按照年龄大小升序排列
}
});
1
2
3
4
5
2
3
4
5
# Python
# 排序
列表排序
a = [3, 1, 2]
a.sort() # 原地排序,升序
# a变为[1, 2, 3]
b = sorted(a) # 返回新列表,原列表不变
# b为[1, 2, 3], a保持不变
1
2
3
4
5
6
2
3
4
5
6
降序排序
a.sort(reverse=True) # 原地降序排序
b = sorted(a, reverse=True) # 返回新降序列表
1
2
2
自定义排序
# 按字符串长度排序
words = ['apple', 'banana', 'cherry']
words.sort(key=lambda x: len(x))
# 结果为['apple', 'cherry', 'banana']
# 多级排序
students = [('Tom', 20), ('Alice', 18), ('Bob', 20)]
students.sort(key=lambda x: (x[1], -x[0])) # 先按年龄升序,再按姓名降序
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# heapq
导包
import heapq
1
构建堆
a = [1,2,3]
heapq.heapify(a)
1
2
2
插入元素
heapq.heappush(a, 4) # 将元素4插入堆中
1
弹出堆顶元素
min_val = heapq.heappop(a) # 弹出并返回堆中的最小元素
1
peek操作, 获取最小元素
min_val = a[0] # 获取堆中的最小元素,但不弹出
1
tip: 请注意,python的heapq默认提供的是最小堆,如果需要使用最大堆,请在为所有元素添加'-'号 例如: [1, 2, 3] -> [-1, -2, -3]. 这样在构建heap的时候,依然会按照最小堆的规则构建,但弹出元素时会先把-3弹出来。去除负号后得到3
# 将数字变为二进制字符串
num = 10 # 十进制数字
binary_str = bin(num)[2:] # 转换为二进制字符串,去掉前缀'0b'
print(binary_str) # 输出结果为 '1010'
1
2
3
2
3
# 字符通过ASCII码加整数
chr(ord('a') + 1)
# 'b'
1
2
2
ord()
可以把字符转换为ASCII码
# map
# 初始化
# 初始化一个空的map
my_map = dict()
1
2
2
# 将字典的键转换为列表
d = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(d.keys())
print(keys_list) # 输出:['a', 'b', 'c']
1
2
3
2
3
# 将字典的值转换为列表
d = {'a': 1, 'b': 2, 'c': 3}
values_list = list(d.values())
print(values_list) # 输出:[1, 2, 3]
1
2
3
2
3
# 将字典的键值对转换为列表
d = {'a': 1, 'b': 2, 'c': 3}
items_list = list(d.items())
print(items_list) # 输出:[('a', 1), ('b', 2), ('c', 3)]
1
2
3
2
3
# 遍历字典
d = {'a': 1, 'b': 2, 'c': 3}
for key, value in d.items():
print(key, value)
# 输出:
# a 1
# b 2
# c 3
1
2
3
4
5
6
7
2
3
4
5
6
7
# C++
# 数组排序
升序
int a[] = {3, 1, 2};
int n = sizeof(a) / sizeof(a[0]); // 计算数组长度
sort(a, a + n); // 对数组进行排序,升序
// a变为{1, 2, 3}
1
2
3
4
2
3
4
降序
int a[] = {3, 1, 2};
int n = sizeof(a) / sizeof(a[0]); // 计算数组长度
sort(a, a + n, [](int x, int y) {
return x > y; // 使用lambda表达式实现降序
});
// a变为{3, 2, 1}
1
2
3
4
5
6
2
3
4
5
6
# vector排序
升序
#include <vector>
#include <algorithm>
std::vector<int> vec = {3, 1, 2};
sort(vec.begin(), vec.end()); // 对vector进行排序,升序
// vec变为{1, 2, 3}
1
2
3
4
5
6
2
3
4
5
6
降序
#include <vector>
#include <algorithm>
std::vector<int> vec = {3, 1, 2};
sort(vec.begin(), vec.end(), [](int x, int y) {
return x > y; // 使用lambda表达式实现降序
});
// vec变为{3, 2, 1}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 复杂对象自定义排序
struct Student {
std::string name;
int score;
};
std::vector<Student> students = {
{"Alice", 88},
{"Bob", 95},
{"Charlie", 88},
{"David", 72}
};
/**
* 自定义排序规则:
* 1. 按成绩降序
* 2. 成绩相同时,按姓名字典序升序
* 如果记不住lambda表达式咋写,可以记住左边在左边,右边在右边。小于号(<),是升序;大于号(>),是降序
* 例如:return a.name < b.name; 左边(a)在左边,右边(b)在右边,加上小于号(<),就是升序
* 例如:return a.score > b.score; 左边(a)在左边,右边(b)在右边,加上大于号(>),就是降序
*/
sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
if (a.score != b.score) {
return a.score > b.score; // 按成绩降序
}
return a.name < b.name; // 成绩相同时按姓名字典序升序
});
// 排序后的students:
// Bob (95)
// Alice (88)
// Charlie (88)
// David (72)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
帮助我们改善此页面! (opens new window)
上次更新: 2025/04/25, 04:47:03