[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];
    }
}
相关推荐
我材不敲代码2 分钟前
Python 函数核心:位置参数与关键字参数详解
java·前端·python
wuweijianlove16 分钟前
算法设计中的空间复用与数据对齐优化的技术5
算法
qq_3331209734 分钟前
C++高并发内存池的整体设计和实现思路_C 语言
java·c语言·c++
mh_f37 分钟前
33.批量通过GET链接下载图片到指定文件夹下
java
金銀銅鐵39 分钟前
[Java] 如何理解 class 文件中方法的 access flags?
java·后端
智研数智工坊39 分钟前
SpringBoot4.0.6 + Security7.x + JWT 最新完整实战|无状态权限认证、统一异常处理、可直接落地
java·spring boot·spring security·jwt·权限认证
DIY源码阁42 分钟前
JavaSwing宿舍管理系统 - MySQL版
java·数据库·mysql·eclipse
Han_han91943 分钟前
递归相关题目:
java
yuan199971 小时前
基于 MATLAB PSO 工具箱的函数寻优算法
开发语言·算法·matlab
YUANQIANG20241 小时前
博弈论中势函数与势博弈构造:为什么看似 “先射箭后画靶”
算法·信息与通信