leetcode上java编程常用方法

数组排序

int[] arr = new int[k];
Arrays.sort(arr);

有序列表

List<Integer> list = new ArrayList();
Collections.reverse(list);//翻转列表顺序
list.toArray(new int[list.size()];//List转为数组
List<String> list = new ArrayList<String>(Arrays.asList(array));//数组转为List集合,该方法只用于String类型。对于int[]数组不好使,int和Integer相互转换无法操作

链表

LinkedList<Integer> list = new LinkedList();
list.addFirst(item);在列表开头插入元素
list.addLast(item);在列表结尾插入元素
list.contains(item);列表是否包含指定元素
list.get(index);获取列表中指定位置处的元素
list.getFirst();获取列表第一个元素
list.getLast();获取列表最后一个元素
list.size();获取列表中元素个数

哈希集合

HashSet<Integer> set = new HashSet();
set.contains()
set.add()

Deque<TreeNode> stack = new LinkedList();
//也可以用 Stack<Integer> stack = new Stack();
stack.push();//进栈
stack.pop();//出栈
stack.peek();//查看栈顶对象
stack.empty();//判断栈是否为空

队列

//普通队列
Queue<String> queue = new LinkedList<String>();
queue.offer();//入队列
queue.poll();//出队列
queue.peek();//获取队头元素

//双端队列
Deque<Integer> deque = new LinkedList<>();
deque.isEmpty();//判断空
deque.peekLast();//访问队尾数据
deque.removeLast();//移除队尾数据
deque.addLast(int k);//在队尾插入数据
deque.removeFirst();//移除队头数据
deque.peekFirst();//访问队头数据

哈希表

Map<Integer,Integer> count = new HashMap();
count.put(key,value);//加入键值对
count.get(key);//根据键获取对应值
count.containsKey(key);//是否包含key,返回true/false
count.containsValue(value);//是否包含value,返回true/false
count.size();//map中键值对的数量
count.isEmpty();//map是否为空,返回true/false

PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>()//小顶堆
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11,new Comparator<Integer>(){ 
   @Override
   public int compare(Integer i1,Integer i2){
        return i2-i1;
   }
});// 大顶堆,容量11,需要重写Comparator函数
heap.add();/heap.offer()//插入元素
heap.size();//堆的大小
heap.poll();//弹出元素
heap.isEmpty();
heap.peek();//获取堆顶元素

字符串处理

//字符串拼接
StringBuilder ans = new StringBuilder();
 ans.append("/");
 ans.toString();

//字符串分割
String s = " a b c ";
s = s.trim();//删除首尾空格,s变为"a b c"
String arr[] = s.split(" ");
String arr[] = s.split("\\s+");//多空格混合拆分

 
//字符数组转为字符串
String.valueOf(char[]) 

//字符串取子串
String.substring(开始位置索引,结束位置索引[可省略])

//字符串转为字符数组
String str;
str.toCharArray()

//字符串转为int,double
Integer.parseInt(String);
Double.parseDouble(String);

//int转为String
String.valueOf(int);
Integer.toString(int);

Integer封装类

在使用Integer封装类时,涉及两个Integer对象中值的比较必须使用.equals()方法,==在两个对象的情况下会直接比较地址。如果一边是int,则会自动拆箱,进行值的比较。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小郁同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值