[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];
    }
}
相关推荐
Cx330_FCQ7 小时前
Tmux使用
服务器·git·算法
@航空母舰7 小时前
SpringBoot通过Map实现天然的策略模式
java·spring boot·后端
Co_Hui7 小时前
Java 并发编程
java
拳里剑气8 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa0510308 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1238 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
long3169 小时前
Java 新手入门与实战开发指南
java·开发语言
执笔画流年呀9 小时前
Linux搭建Java项目部署环境
java·linux·运维
程序员天天困9 小时前
Arthas ognl 表达式从入门到实战:掌握在线调试最强的表达式引擎
java·jvm·后端
IT_Octopus10 小时前
Spring Boot 中 ThreadLocal 请求上下文的完整生命周期
java·spring boot·spring