LeetCode刷题必知的Java知识

1.数组操作

//创建数组
int[] a = {1,2,3};

int[] b = new int[]{1,2,3};

int[] c = new int[3];
for(int i = 0;i < a.length;i++){
    c[i] = i+1;
}

ArrayList<Integer> arr = new ArrayList<>();
for(int i = 0;i < 3;i++){
    arr.add(i+1);
}
//添加元素
arr.add(99);
arr.add(2,99);
//访问元素:通过下标(索引)访问
int c1 = c[1];
int arr1 = arr.get(1);
//更新元素
c[1] = 11;
arr.set(1,11);
//删除元素
arr.remove(3);
//数组长度
int csize = c.length;
int arrsize = arr.size();
//遍历数组
for(int i = 0;i < c.length;i++){
    int current = c[i];

for(int i = 0;i < arr.size();i++){
    int current = arr.get(i);
//数组排序
Arrays.sort(c);
Collections.sort(arr);
Collections.sort(arr,Collections.reverseOrder());

2.链表操作

//创建链表
Linkedlist<Integer> list = new LinkedList<>();
//添加元素
list.add(1);
list.add(2,99);
//访问元素
int element = list.get(2);
//搜索元素
int index = list.indexof(99);
//更新元素
list.set(2,99);
//删除元素
list.remove(2);
//长度
int length = list.size();

3.队列操作

//创建队列
Queue<Integer> queue = new LinkedList<>();
//添加元素
queue.add(1);
//获取即将出队的元素
int temp1 = queue.peek();
//删除即将出队的元素
int temp2 = queue.poll();
//判断队列是否为空
queue.isEmpty();
//队列长度
queue.size();
//遍历队列
while(!queue.isEmpty()){
    int temp = queue.poll();
    System.out.println(temp);
}

4.栈操作

//创建栈
Stack<Integer> stack = new Stack<>();
//添加元素
stack.push(1);
//获取栈顶元素
stack.peek();
//删除栈顶元素
int temp = stack.pop();
//栈是否为空
stack.isEmpty();
//栈的遍历(边删除边遍历)
while(!stack.isEmpty()){
    int num = stack.pop();
    System.out.println(num);
}

5.哈希表操作

//创建哈希表
String[] hashTable = new String[4];
HashMap<Integer,String> map = new HashMap<>();
//添加元素
hashTable[1] = "lihua";
map.put(1,"lihua");
//更新元素
hashTable[1] = "lisi";
map.put(1,"lisi");
//删除元素
hashTable[1] = "";
map.remove(1);
//获取元素
String temp = hashTable[3];
map.get(3);
//检查key是否存在
map.containsKey(3);
//长度,是否还有函数
map.size();
map.isEmpty():

6.哈希集合操作

//创建集合
HashSet<Integer> set = new HashSet<>();
//添加元素
set.add(1);
//搜索元素
set.contains(2);
//删除元素
set.remove(1);
//长度
set.size();

7.堆操作

//创建堆
import java.util.PriorityQueue;
//创建最小堆
PriorityQueue<Integer> minheap = new PriorityQueue<>();
//创建最大堆
PriorityQueue<Integer> maxheap = new PriorityQueue<>(Collections.reverseOrder());
//添加元素
minheap.add(1);
maxheap.add(20);
//堆顶元素
minheap.peek();
//删除堆顶元素
minheap.poll();
//堆的大小
minheap.size();
//遍历堆
while(!minheap.isEmpty()){
    System.out.println(minheap.poll());
}

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值