笨蛋学算法之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);
        }
    }
}
相关推荐
m0_743470371 分钟前
高性能计算框架实现
开发语言·c++·算法
前端的阶梯2 分钟前
深入浅出的聊下AI Agent
算法·架构
1104.北光c°3 分钟前
基于Canal + Kafka的高可用关注系统:一主多从关系链
java·开发语言·笔记·分布式·程序人生·kafka·一主多从
Tony沈哲4 分钟前
AI 正在进入本地时代,我开源了一个推理平台—— 支持多模型 / Agent / Workflow 的工程实现
人工智能·算法·llm
黎阳之光4 分钟前
AI赋能安全新生态 黎阳之光锚定国家政策筑造数智防线
大数据·人工智能·算法·安全·数字孪生
Mem0rin4 分钟前
[Java]异常及其处理
java·开发语言
skiy5 分钟前
Spring boot创建时常用的依赖
java·spring boot·后端
01二进制代码漫游日记5 分钟前
通讯录(一)
c语言·数据结构·学习
早起的年轻人7 分钟前
告别Git仓库臃肿:一招解决Maven target目录误提交问题
java·git·maven
2401_846341658 分钟前
调试技巧与核心转储分析
开发语言·c++·算法