Java算法做题中用到的-数据结构(对应C++的STL)【java中各种集合的api方法】

Java算法做题中用到的-数据结构(对应C++的STL)

    • 一、数组List
      • 初始化
        • [加入元素: add](#加入元素: add)
        • [删除元素: remove(参数是角标)](#删除元素: remove(参数是角标))
        • 获取元素:get
        • [indexOf() 返回指定元素下标](#indexOf() 返回指定元素下标)
        • contains()
        • toArray()
      • 排序
        • [方法一:数组排序Comparator<Integer> cmp](#方法一:数组排序Comparator cmp)
        • [方法二:List排序 Collections.sort(arrayMap);](#方法二:List排序 Collections.sort(arrayMap);)
      • [去重 arrayMap = new ArrayList<>(new HashSet<>(arrayMap));](#去重 arrayMap = new ArrayList<>(new HashSet<>(arrayMap));)
      • [indexof的时间复杂度是 o(N)](#indexof的时间复杂度是 o(N))
    • [二、优先队列 PriorityQueue](#二、优先队列 PriorityQueue)
    • [三、 String](#三、 String)
    • 四、超时问题
    • [五、类排序问题(数组用arrays list用collections)](#五、类排序问题(数组用arrays list用collections))
      • [1. 类自身实现 Comparable 实现comparaTo方法](#1. 类自身实现 Comparable 实现comparaTo方法)
      • [2. 定制排序 Comparator](#2. 定制排序 Comparator)
      • [3. 简化Comparator](#3. 简化Comparator)
    • 六、Deque
    • 七、输入输出
    • 八、Collections
    • 九、Queue
    • 十、Set
    • 十一、Stack

一、数组List

初始化

java 复制代码
List<Integer> list = new ArrayList<>();
加入元素: add
删除元素: remove(参数是角标)
获取元素:get
indexOf() 返回指定元素下标
contains()
toArray()

排序

方法一:数组排序Comparator cmp
java 复制代码
// import java.util.*;

class Solution {

    static Comparator<Integer> cmp = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1,Integer o2) {
            String s1 = o1+""+o2;
            String s2 = o2+""+o1;
            return s1.compareTo(s2);
        }
    };

    public String printMinNumber(int[] nums) {
        String res = "";
        Integer[] list = new Integer[nums.length];
        int n = nums.length;
        for(int i = 0; i < n; i++){
            list[i] = nums[i];
        }
        Arrays.sort(list,cmp);
        for(int i = 0; i < n; i++){
            res += list[i]+"";
        }
        return res;

    }
}
方法二:List排序 Collections.sort(arrayMap);

去重 arrayMap = new ArrayList<>(new HashSet<>(arrayMap));

indexof的时间复杂度是 o(N)

二、优先队列 PriorityQueue

java 复制代码
peek()//返回队首元素
poll()//返回队首元素,队首元素出队列
add()//添加元素
size()//返回队列元素个数
isEmpty()//判断队列是否为空,为空返回true,不空返回false
java 复制代码
static Comparator<Integer> cmp = new Comparator<Integer>() {
      public int compare(Integer e1, Integer e2) {
        return e2 - e1;
      }
    };
public static void main(String[] args) {
        //不用比较器,默认升序排列
        Queue<Integer> q = new PriorityQueue<>();
        q.add(3);
        q.add(2);
        q.add(4);
        while(!q.isEmpty())
        {
            System.out.print(q.poll()+" ");
        }
        /**
         * 输出结果
         * 2 3 4 
         */
        //使用自定义比较器,降序排列
        Queue<Integer> qq = new PriorityQueue<>(cmp);
        qq.add(3);
        qq.add(2);
        qq.add(4);
        while(!qq.isEmpty())
        {
            System.out.print(qq.poll()+" ");
        }
        /**
         * 输出结果
         * 4 3 2 
         */
}
java 复制代码
PriorityQueue<Integer> queue1 = 
		new PriorityQueue<Integer>();
queue1.add(10);
queue1.add(8);
System.out.println(queue1.poll()); // 8
PriorityQueue<Integer> queue2 = 
		new PriorityQueue<Integer>((o1,o2) -> o1 - o2);
queue2.add(10);
queue2.add(8);
System.out.println(queue2.poll()); // 8
PriorityQueue<Integer> queue3 = 
		new PriorityQueue<Integer>((o1,o2) -> o2 - o1);
queue3.add(10);
queue3.add(8);
System.out.println(queue3.poll()); // 10

三、 String

  1. cpp中的si 在java中是 s.charAt(i);

四、超时问题

  1. 使用print 和 println 别用 printf
  2. 使用二分

五、类排序问题(数组用arrays list用collections)

1. 类自身实现 Comparable 实现comparaTo方法

java 复制代码
package compare;

public class Goods implements Comparable{
    private String name;
    private double price;

    public Goods() {
    }
    
    public Goods(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    //重写compareTo方法,并指明排序的方式:先按价格从低到高排序,再按名称从高到低排序
    @Override
    public int compareTo(Object o) {
        //instanceof ,用来测试对象0是否为Goods类的实例
       if (o instanceof Goods){
           Goods goods = (Goods) o;
           if (this.price > goods.price){
               return 1;
           } else if (this.price < goods.price){
               return -1;
           }else {
               return -this.name.compareTo(goods.name);
           }
       }
       throw new RuntimeException("输入类型错误,无法比较");
    }
}

2. 定制排序 Comparator

java 复制代码
String[] str = new String[]{"aa","kk","dd","cc"};
Arrays.sort(str, new Comparator<String>() {
    @Override
    //从大到小进行排序
    public int compare(String o1, String o2) {
        return -o1.compareTo(o2);
    }
});
System.out.println(Arrays.toString(str));//[kk, dd, cc, aa]

3. 简化Comparator

java 复制代码
//Arrays.sort(range, 0, n, (o1, o2) -> o1.r - o2.r);

六、Deque

addFirst(): 向队头插入元素,如果元素为空,则发生NPE(空指针异常)

addLast(): 向队尾插入元素,如果为空,则发生NPE

offerFirst(): 向队头插入元素,如果插入成功返回true,否则返回false

offerLast(): 向队尾插入元素,如果插入成功返回true,否则返回false

removeFirst(): 返回并移除队头元素,如果该元素是null,则发生NoSuchElementException

removeLast(): 返回并移除队尾元素,如果该元素是null,则发生NoSuchElementException

pollFirst(): 返回并移除队头元素,如果队列无元素,则返回null

pollLast(): 返回并移除队尾元素,如果队列无元素,则返回null

getFirst(): 获取队头元素但不移除,如果队列无元素,则发生NoSuchElementException

getLast(): 获取队尾元素但不移除,如果队列无元素,则发生NoSuchElementException

peekFirst(): 获取队头元素但不移除,如果队列无元素,则返回null

peekLast(): 获取队尾元素但不移除,如果队列无元素,则返回null

pop(): 弹出栈中元素,也就是返回并移除队头元素,等价于removeFirst(),如果队列无元素,则发生NoSuchElementException

push(): 向栈中压入元素,也就是向队头增加元素,等价于addFirst(),如果元素为null,则发生NPE,如果栈空间受到限制,则发生IllegalStateException

七、输入输出

java 复制代码
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);

八、Collections

文章

九、Queue

十、Set

十一、Stack

相关推荐
旖-旎5 分钟前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
我命由我123451 小时前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑1 小时前
Sentinel安装
java·后端·微服务
轻颂呀1 小时前
约瑟夫环问题
算法
凤凰院凶涛QAQ3 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
科技大视界3 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴3 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe3 小时前
算法滑动窗口
数据结构·算法
掘金_答案3 小时前
上线那天,一个 ConcurrentHashMap 差点送走我的 AI 客服——3 天排查 JVM 血泪史
java·后端·架构
怪兽学LLM3 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展