代码随想录算法训练营第六天 |242.有效的字母异位词 、349. 两个数组的交集、202. 快乐数、1. 两数之和

使用数组来做哈希的题目是由于题目限制数组大小,如果分散的话不要使用数组,会造成极大的空间浪费

242.有效的字母异位词

题目链接:242.有效的字母异位词

  • 暴力法

  • 哈希法 长度26的数组

349. 两个数组的交集

题目链接:349. 两个数组的交集

  • 用set解决题目

202. 快乐数

题目链接:202. 快乐数

  • 用哈希集合检测循环

1. 两数之和

题目链接:1. 两数之和https://leetcode.cn/problems/happy-number/)

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

© 版权声明

相关文章

暂无评论

none
暂无评论...