zoukankan      html  css  js  c++  java
  • 力扣202题、349题、1题(哈希表)

    202、快乐数

    基本思想:

    题目是中说如果平方和变不到1的话可能会无限循环

    说明求和过程中,和 会重复出现

    判断一个元素是否出现在集合里的时候,就要考虑哈希表

    具体实现:

    只要record重复出现一次就退出循环,得出不是快乐数的结论

    要会分解一个数

    代码:

    class Solution {
        public boolean isHappy(int n) {
            Set<Integer> record = new HashSet<>();
            while (n != 1 && !record.contains(n)) {
                record.add(n);
                n = getNextNumber(n);
            }
            return n == 1;
        }
    
        private int getNextNumber(int n) {
            int res = 0;
            while (n > 0) {
                int temp = n % 10;
                res += temp * temp;
                n = n / 10;
            }
            return res;
        }
    }

     349、两个数组的交集

    基本思想:

    HashSet

    具体实现:

    输出每一个元素一定是唯一的,也就是说输出的结果去重,可以不考虑输出结果的顺序

    所以要使用HashSet

    代码:

    class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0){
                return new int[0];
            }
            Set<Integer> set1 = new HashSet<>();
            Set<Integer> resSet = new HashSet<>();
            for (int i : nums1){
                set1.add(i);
            }
            for (int i : nums2){
                if (set1.contains(i)){
                    resSet.add(i);
                }
            }
            int[] resArr = new int[resSet.size()];
            int index = 0;
            for (int i : resSet){
                resArr[index++] = i;
            }
            return resArr;
        }
    }

    1、两数之和

    基本思想:

    HashMap

    具体实现:

    nums = [2,7,11,15]

    下标:   0,1, 2, 3          target =9

    定义一个HashMap,map<数值,下标>

    循环遍历数组:

    i = 0时,9-nums[0] = 7,寻找target - nums[i]是否在map中

    7不在map中,所以把nums[0]和下标0放入map中

    i = 1时,9-nums[1] = 2,寻找target - nums[i]是否在map中

    2在map中,所以得到2和7的下标0和1

     代码:

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] res = new int[2];
            if(nums == null || nums.length == 0){
                return res;
            }
            Map<Integer, Integer> map = new HashMap<>();
            for(int i = 0; i < nums.length; i++){
                int temp = target - nums[i];
                if(map.containsKey(temp)){
                    res[1] = i;
                    res[0] = map.get(temp);
                }
                map.put(nums[i],i);
            }
            return res;
        }
    }
  • 相关阅读:
    IDEA实用教程(十一)—— 使用Maven创建JavaSE项目
    IDEA实用教程(十)—— 配置Maven的全局设置
    IDEA实用教程(九)—— 创建Servlet
    IDEA实用教程(八)—— 创建JavaWeb项目
    搭建视频解析的接口
    IDEA实用教程(七)—— IDEA的断点调试
    Elasticsearch 常用配置参数总结
    C# web api返回类型设置为json的两种方法
    asp.net MVC 中@Html.Partial,@Html.Action,@Html.RenderPartial,@Html.RenderAction区别
    CountDownLatch的使用和原理解析
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15483634.html
Copyright © 2011-2022 走看看