笨蛋学算法之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);
        }
    }
}
相关推荐
Traving Yu7 分钟前
JVM 底层与调优
java·jvm
董董灿是个攻城狮7 分钟前
5分钟搞懂微调的能力退化问题
算法
三棱球9 分钟前
Java 基础教程 Day2:从数据类型到面向对象核心概念
java·开发语言
indexsunny11 分钟前
互联网大厂Java面试实录:微服务+Spring Boot在电商场景中的应用
java·spring boot·redis·微服务·eureka·kafka·spring security
wuminyu14 分钟前
专家视角看Java线程生命周期与上下文切换的本质
java·linux·c语言·jvm·c++
程序猿乐锅23 分钟前
Java第十三篇:Stream流
java·笔记
穿条秋裤到处跑25 分钟前
每日一道leetcode(2026.04.19):下标对中的最大距离
算法·leetcode·职场和发展
林三的日常26 分钟前
SpringBoot + Druid SQL Parser 解析表名、字段名(纯Java,最佳方案)
java·spring boot·sql
deviant-ART31 分钟前
java stream 的 findFirst 和 findAny 踩坑点
java·开发语言·后端
Sag_ever37 分钟前
时间复杂度与空间复杂度超详细入门讲解
算法