[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];
    }
}
相关推荐
bingd011 小时前
慕课网、CSDN、菜鸟教程…2026 国内编程学习平台实测对比
java·开发语言·人工智能·python·学习
somi71 小时前
ARM-驱动-09-LCD FrameBuffer
arm开发·驱动开发·算法·自用
大飞哥~BigFei1 小时前
缓存一致性终极解决方案之Facebook租约机制的开源实现集成改造
java·缓存·开源
乐迪信息1 小时前
乐迪信息:智慧港口AI防爆摄像机实现船舶违规靠岸自动抓拍
大数据·人工智能·算法·安全·目标跟踪
凌冰_1 小时前
Thymeleaf 核心语法详解
java·前端·javascript
winxp-pic1 小时前
图片校正软件 操作说明及算法介绍
算法
AIBox3651 小时前
claude 镜像 api 使用指南(2026 年4 月更新)
java·服务器·前端·人工智能·gpt·前端框架
极光代码工作室1 小时前
基于SpringBoot的在线考试系统
java·springboot·web开发·后端开发
Gopher_HBo1 小时前
CompletableFuture运用原理
java·后端