笨蛋学算法之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);
        }
    }
}
相关推荐
程序员三明治6 分钟前
【AI】Java 调用大模型 API 实战:从 OpenAI 协议到 SiliconFlow 流式响应解析
java·开发语言·人工智能
Zzzzmo_7 分钟前
前缀和算法
算法·前缀和
睡觉就不困鸭8 分钟前
第十八天 有效的括号
数据结构·算法
_日拱一卒9 分钟前
LeetCode:148排序链表
算法·leetcode·链表
2501_9130613416 分钟前
JVM虚拟机——面试中的八股文
java·jvm·面试
A-Jie-Y16 分钟前
JAVA设计模式-单例模式
java·设计模式
编程之升级打怪17 分钟前
设计模板引擎类的主要接口
java
IpdataCloud18 分钟前
IP查询工具的准确率怎么评估?一份可上生产的选型与验收指南
网络·人工智能·算法
ffqws_24 分钟前
Spring Boot 整合 PageHelper 实现分页查询
java·spring boot·mybatis
大龄码农-涵哥27 分钟前
Java调用AI大模型API入门:从零开始接入ChatGPT/通义千问
java·人工智能·chatgpt