当前位置: 首页 > news >正文

哈希表系列一>两数之和

目录

  • 题目:
  • 方法:
  • 暴力代码:
  • 优化后代码:

题目:

链接: link这里是引用

方法:

这里是引用


在这里插入图片描述

暴力代码:

public int[] twoSum(int[] nums, int target) {
        解法一:暴力解法:
        int n = nums.length;
        for(int i = 1; i <= n; i++)
            for(int j = i-1; j >= 0; j--){
                if(target == nums[i] + nums[j]){
                    return new int[]{i,j};
                }
            }

        return null;    
 }

优化后代码:

class Solution {
        //解法二:用哈希表优化:
        Map<Integer,Integer> hash = new HashMap<>();//<nums[i],i>
        
        for(int i = 0; i < nums.length; i++){
            int find = target - nums[i];
            if(hash.containsKey(find)){
                return new int[]{i,hash.get(find)};
            }
            hash.put(nums[i],i);
        }

        return null;
    }
}

相关文章:

  • 网站建设运作流程网络营销实施方案
  • weebly 与wordpress自媒体seo优化
  • 做设计在哪个网站接单搜索引擎网站推广如何优化
  • 怎么自己做直播网站吗外贸找客户有什么网站
  • 汕头网站开发定制怎么推广自己的公司
  • 搭建网站用什么软件seo信息是什么
  • Linux | 无头 Linux 服务器安装和设置
  • CentOS 7 强制升级Docker 24.x终极指南(解决MySQL8镜像兼容性问题)
  • 基础常问 (概念、代码)
  • 【C++】多态功能细节问题分析
  • 什么是宽带拨号?
  • java中任务调度java.util.Timer,ScheduledExecutor,Quartz的机制说明和demo代码实例分享
  • Vue 3 中按照某个字段将数组分成多个数组
  • duckdb、PG、Faiss和Milvus调研与对比
  • 液态神经网络技术指南
  • C语言实现简单的控制台贪吃蛇游戏精讲
  • PowerBI中常用的时间智能函数
  • 【Linux】命令和权限
  • RHCSA Linux 系统删除文件
  • 编译出来的kernel功能与.config一致还是 defconfig一致
  • ASM1042A型CANFD芯片通信可靠性研究
  • Mysql篇(三):SQL优化经验全方位解析
  • 算法设计学习7
  • 【Axure元件分享】年月日范围选择器
  • 使用MQTTX软件连接阿里云
  • 基于卷积神经网络CNN实现电力负荷多变量时序预测(PyTorch版)