[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];
    }
}
相关推荐
血小板要健康8 分钟前
二叉树 dfs 题型总结
算法·深度优先
wifi___4 小时前
全局异常处理的原理
java·开发语言
我变成萤火虫5 小时前
河南萌新联赛2026第(四)场:南阳理工学院
数据结构·c++·算法·贪心算法·stl·动态规划
To_OC8 小时前
LC 239 滑动窗口最大值:从暴力超时到单调队列一遍过
javascript·算法·leetcode
2601_963870208 小时前
【计算机毕业设计】基于Spring Boot的专科医院医疗管理系统
java·spring boot·课程设计
Bingo_BIG8 小时前
Java Spring 批量修改,实体、接口、方法的定义
java·spring
.道阻且长.9 小时前
9.LeetCode算法习题讲解--滑动窗口--无重复字符的最长字串
算法·leetcode·职场和发展·哈希算法
画中有画9 小时前
软件架构中质量属性(性能、安全、可扩展性)的权衡设计
java·运维·安全
Shaoxi Zhang9 小时前
JAVA学习笔记035——对象和JSON格式
java·笔记·学习
赵丙双9 小时前
CountDownLatch 源码分析
java·aqs·countdownlatch