[Java][Leetcode simple] 1. 两数之和

1. 两重循环

o N^2

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        int[] res = new int[2];
        for(int i=0;i<n;i++){
            for(int j =0;j<n;j++){
                if( i != j && nums[i]+ nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }

        return res;
    }
}

2. HashMap

  1. 放入HaspMap
  2. 从中是否有合适的
java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0;i<n;i++){
           map.put(nums[i], i);
        }

        for(int i=0;i<n;i++){
           Integer j = map.get(target - nums[i]);
           if(j != null && i!=j){
               res[0] = i;
               res[1] = j;

               return res;
           }
        }
         return  res;
    }
}

3. 官解2,确实比我自己想的要精妙

把i当作第二个因子,如果存在解,那么第一个因子肯定已经放入map中了。所以可以大胆的一遍查找,一边填充元素

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;

        Map<Integer, Integer> map = new HashMap<>();
       

        for(int i=0;i<n;i++){
            int j = target - nums[i];
            if(map.containsKey(j)){
                return new int[]{i, map.get(j)};
            }
            map.put(nums[i], i);
        }
         return  new int[0];
    }
}
相关推荐
Je1lyfish6 小时前
CMU15-445 (2025 Fall/2026 Spring) Project#3 - QueryExecution
linux·c语言·开发语言·数据结构·数据库·c++·算法
许彰午6 小时前
03-二叉树——从递归遍历到非递归实现
java·算法
nj01286 小时前
Spring 循环依赖详解:三级缓存、早期引用、AOP 代理与懒加载
java·spring·缓存
Brilliantwxx7 小时前
【C++】 vector(代码实现+坑点讲解)
开发语言·c++·笔记·算法
野生技术架构师7 小时前
2026年最全Java面试题及答案汇总(建议收藏,面试前看这篇就够了)
java·开发语言·面试
一只叫煤球的猫8 小时前
ThreadForge 源码解读一:ThreadScope 如何把并发任务放进清晰边界?
java·面试·开源
洛_尘8 小时前
Python 5:使用库
java·前端·python
程序员小假8 小时前
HTTP3 性能更好,为什么内网微服务依然多用 HTTP2?HTTP2 内网优势是什么?
java·后端
Mr数据杨8 小时前
【Codex】用教案主体模块沉淀标准化教学设计内容
java·开发语言·django·codex·项目开发
NorburyL8 小时前
DPO笔记
深度学习·算法