HashMap

1.HashMap介绍:

  • Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).(创建一个默认初始化容量为16,默认加载因子为0.75的空散列表)

  • 容量是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度
  • HashMap的继承关系

    package java.util;
    import java.io.*;
    public class HashMap<K,V>
        extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable{
    }

     HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。

     

  • 实现不同步,线程不安全

2.HashMap用法:

  • HashMap构造函数:
    // 默认构造函数。
    HashMap()
    // 指定“容量大小”的构造函数
    HashMap(int capacity)
    // 指定“容量大小”和“加载因子”的构造函数
    HashMap(int capacity, float loadFactor)
    // 包含“子Map”的构造函数
    HashMap(Map<? extends K, ? extends V> map) 
  • HashMap接口:
    void                 clear()
    Object               clone()
    boolean              containsKey(Object key)
    boolean              containsValue(Object value)
    Set<Entry<K, V>>     entrySet()
    V                    get(Object key)
    boolean              isEmpty()
    Set<K>               keySet()
    V                    put(K key, V value)
    void                 putAll(Map<? extends K, ? extends V> map)
    V                    remove(Object key)
    int                  size()
    Collection<V>        values() 

3.LeetCode相关题目:

two-sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

4.参考代码:

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值