笨蛋学算法之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);
        }
    }
}
相关推荐
爱跳舞的烤冷面13 分钟前
自学嵌入式第22天(数据结构——哈希)
数据结构·算法·哈希算法
猎嘤一号32 分钟前
博弈论(Game Theory)的理论、算法与工程
人工智能·算法·安全·博弈论
马拉AI1 小时前
腾讯开源 Agent 记忆系统,AI“换对话就忘”的问题有了新解法(附安装使用教程)
人工智能·算法·开源·科研
MC皮蛋侠客2 小时前
Redis 系列(一):全景与最小闭环——从 `SET` 命令到内存数据结构
数据结构·数据库·redis
疯狂打码的少年2 小时前
【数据结构】队列:定义、顺序队列与链式队列
数据结构·笔记
离陌在学C#2 小时前
C# 重载与重写:深入理解面向对象编程的核心概念
java·c#
地平线开发者2 小时前
征程6工具链模型X86推理方式说明
算法
洛阳泰山2 小时前
AI 应用层被 Python 卷成红海,为什么我偏要用 Java 造一个 RAG + 工作流引擎?
java·人工智能·后端
地平线开发者3 小时前
【征程6】校准量化中HistogramObserver解析
算法
二十雨辰3 小时前
[Java]-Spring面试题
java·开发语言