笨蛋学算法之LeetCodeHot100_1_两数之和(Java)

java 复制代码
package com.lsy.leetcodehot100;

public class _Hot1_两数之和 {
    //自写方法
    public static int[] twoSum1(int[] nums, int target) {
        //定义存放返回变量的数组
        int[] arr = new int[2];
        //遍历整个数组
        for (int i = 0; i < nums.length; i++) {
            //从第二个数开始相加判断
            for (int j = 1; j < nums.length; j++) {
                //如果相加的值相等的话就返回数组
                if (nums[i] + nums[j] == target) {
                    arr[0] = i;
                    arr[1] = j;
                    return arr;
                }
            }
        }
        //如果没有的话就返回null
        return null;
    }

    //其他方法
    public static int[] twoSum2(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            //计算出两数中的数A
            int temp = target - nums[i];
            for (int j = 0; j < nums.length; j++) {
                if (i == j) {
                    continue;
                }
                //如果当前的这个数A等于数B说明两个值就是正确的结果
                //temp是数A,nums[j]是数B
                if(temp == nums[j]){
                    return new int[]{i,j};
                }
            }
        }
        //如果没有的话就返回null
        return null;
    }

    public static void main(String[] args) {

        int[] arr = {2, 6, 5, 8, 12, 7, 11, 9};
        int[] result = twoSum1(arr, 14);

        for (int item : result) {
            System.out.println(item);
        }
    }
}
相关推荐
日月云棠2 小时前
各版本JDK对比:JDK 25 特性详解
java
爱理财的程序媛3 小时前
openclaw 盯盘实践
算法
用户8307196840823 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide4 小时前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家4 小时前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺4 小时前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户908324602734 小时前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程5 小时前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
MobotStone6 小时前
Google发布Nano Banana 2:更快更便宜,图片生成能力全面升级
算法
程序员清风9 小时前
用了三年AI,我总结出高效使用AI的3个习惯!
java·后端·面试