天天看点

力扣做题系列——哈希表

HashMap

两数之和

网址:

https://leetcode-cn.com/problems/two-sum/

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] arr = new int[2];
        int i = 0;
        for(i = 0;i < nums.length; i++){
            map.put(nums[i], i);
        }
        for(i=0;i<nums.length;i++){
            int diff=target-nums[i];
            //containsKey() 方法检查 hashMap 中是否存在指定的 key 对应的映射关系。
            //获取指定 key 对应对 value
            if(map.containsKey(diff) && map.get(diff) != i){
                arr[0]=i;
                arr[1]=map.get(diff);
                return arr;
            }
        }
        return arr;
    }
}
           

主要元素

https://leetcode-cn.com/problems/find-majority-element-lcci/

getOrDefault(Object key, V defaultValue):当 Map 集合中有这个 key 时,就使用这个 key 值;如果没有就使用默认值 defaultValue

class Solution {
    public int majorityElement(int[] nums) {
        int n = nums.length;
        int n2 = n/2;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        // getOrDefault(Object key, V defaultValue):当 Map 集合中有这个 key 时,就使用这个 key 值;如果没有就使用默认值 defaultValue
        for (int x : nums) {
            map.put(x, map.getOrDefault(x, 0) + 1);
            if (map.get(x) > n2){
                return x;
            }
        }        
        return -1;
    }
}
           

Set

判定字符是否唯一

https://leetcode-cn.com/problems/is-unique-lcci/

class Solution {
    public boolean isUnique(String astr) {
        Set<Character> set = new HashSet<>();
        char[] chars = astr.toCharArray();
        for (char str : chars) {
            set.add(str);
        }
        int a = set.size();
        int b = astr.length();
        if(a < b){
            return false;
        }
        return true;

    }
}