【LeetCode】数组——hashmap的妙用

在遇到一类题目时,通过双for循环也可暴力破解,但我们可以通过用hashmap来代替一次for循环节约时间开支,在算法上属于用空间换时间,也能帮助我们更好的理解hashmap这一种重要数据结构,并熟悉hashmap的重要方法。

1.两数之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}

两数之和hashtable.containsKey更像一次隐藏的for循环

219. 存在重复元素219. 存在重复元素

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < nums.length; ++i){
        if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k){
            return true;
        }
        map.put(nums[i], i);
    }
    return false;
    }
}

1512. 好数对的数目
 

class Solution {
    public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}


 

相关推荐

  1. LeetCode数组——hashmap

    2024-05-09 20:12:03       13 阅读
  2. linux | && 和 &

    2024-05-09 20:12:03       18 阅读
  3. 【正则表达式

    2024-05-09 20:12:03       33 阅读
  4. information_schema表

    2024-05-09 20:12:03       21 阅读
  5. auto关键字

    2024-05-09 20:12:03       12 阅读
  6. Go数据结构与实现【HashMap

    2024-05-09 20:12:03       22 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-09 20:12:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-09 20:12:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-09 20:12:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-09 20:12:03       20 阅读

热门阅读

  1. Github 2024-05-06 开源项目日报 Top10

    2024-05-09 20:12:03       11 阅读
  2. Springboot整合Minio,2024版教程

    2024-05-09 20:12:03       11 阅读
  3. 【android systrace学习】

    2024-05-09 20:12:03       11 阅读
  4. MySQL中SELECT语句的执行流程详解

    2024-05-09 20:12:03       10 阅读
  5. BL120协议Modbus RTU和Modbus TCP互转

    2024-05-09 20:12:03       11 阅读
  6. mybatis 批量添加数据

    2024-05-09 20:12:03       8 阅读
  7. Utreexod:支持Utreexo累加器的比特币全节点

    2024-05-09 20:12:03       12 阅读
  8. 解决报错HTTPError: HTTP Error 403: Forbidden

    2024-05-09 20:12:03       11 阅读
  9. TypeScript基础:类型系统介绍

    2024-05-09 20:12:03       11 阅读