[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];
    }
}
相关推荐
用户3521802454751 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
vivo互联网技术1 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
东坡白菜1 天前
破局全栈:一个前端开发的Java入门实战记录(1)
java·全栈
唐青枫1 天前
Java Tomcat 实战指南:从 Servlet 容器到 Spring Boot 部署
java
wsaaaqqq1 天前
roudan:自由选择实体、灵活操作数据、快速写入数据库的 Java 框架
java
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
怕浪猫1 天前
Electron 系列文章封面图
算法·架构·前端框架
plainGeekDev1 天前
null 判断 → Kotlin 可空类型
android·java·kotlin