当前位置:   article > 正文

java刷算法题 常用的一些方法_java刷算法题常用技巧

java刷算法题常用技巧

1. 输入输出类

Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println(input);
  • 1
  • 2
  • 3

2. 常用的数据结构

2.1栈

Stack stack = new Stack<>();

System.out.println(stack.empty());
System.out.println(stack.size());

stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);

System.out.println(stack.empty());
System.out.println(stack.size());

//peek查看栈顶元素不用删除  pop弹出栈顶元素
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());

System.out.println(stack.empty());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

2.2 队列

2.2.1 普通队列

Queue queue = new LinkedList();
queue.offer(1);//入队列
queue.offer(2);//入队列
queue.offer(3);//入队列
System.out.println(queue.isEmpty());
System.out.println(queue.peek());//获取队头元素,但是不出队列
System.out.println(queue.poll());//出队列
System.out.println(queue.poll());//出队列
System.out.println(queue.poll());//出队列
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.2.2 双端队列

Deque deque = new LinkedList<>();
deque.isEmpty();//判断空
deque.peekFirst();//访问队头数据
deque.peekLast();//访问队尾数据
deque.addFirst(2);
deque.addLast(1);//在队尾插入数据
deque.removeLast();//移除队尾数据
deque.removeFirst();//移除队头数据
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2.2.3 优先队列

队列中的元素会排序,是通过堆排序实现的

注意:优先级队列插入的元素不能为空

  1. add:插入一个元素,不成功会抛出异常
  2. offer:插入一个元素,不能被立即执行的情况下会返回一个特殊的值(true 或者 false)
  3. remove(E e):删除一个元素,如果不成功会返回false。
  4. poll:出队列
  5. peek:查询队顶元素
  6. indexOf(Object o):查询对象o的索引
  7. contain(Object o):判断是否容纳了元素

3. 列表的变换

3.1 翻转

Collections.reverse(List<?> list)

3.2 排序

Arrays.sort(array)
Arrays.sort(array,comparator)
Collections.sort(list)
Collections.sort(list,comparator)

3.3 批量复制

Arrays.fill()函数
Collections.fill()函数

4.字符串的一些操作

4.1 字符串切割

String str = "are you ok ?";
String[] strings = str.split(" ");
for (int i = 0; i < strings.length; i++) {
    System.out.println(strings[i]);
}
  • 1
  • 2
  • 3
  • 4
  • 5

4.2 第一次所在位置所在的位置

String str = "are you ok ?";

int index1 = str.indexOf('r');
System.out.println(index1);

int index2 = str.indexOf("you");
System.out.println(index2);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4.3 大小写变换

String str = "Are you ok ?";
String upperStr = str.toUpperCase();
String lowerStr = str.toLowerCase();
System.out.println(upperStr);
System.out.println(lowerStr);
  • 1
  • 2
  • 3
  • 4
  • 5

4.4 子字符串

substring

5. 计算

5.1 最大值,最小值

Math.MAX_VALUE
Math.MIN_VALUE

开方 平方

Math.sqrt(x)
Math.pow(x,2)

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号