笨蛋学算法之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);
        }
    }
}
相关推荐
秋说24 分钟前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy37 分钟前
力扣61.旋转链表
算法·leetcode·链表
一只叫煤球的猫1 小时前
【🤣离谱整活】我写了一篇程序员掉进 Java 异世界的短篇小说
java·后端·程序员
斐波娜娜1 小时前
Maven详解
java·开发语言·maven
Bug退退退1231 小时前
RabbitMQ 高级特性之事务
java·分布式·spring·rabbitmq
程序员秘密基地1 小时前
基于html,css,vue,vscode,idea,,java,springboot,mysql数据库,在线旅游,景点管理系统
java·spring boot·mysql·spring·web3
皮皮林5511 小时前
自从用了CheckStyle插件,代码写的越来越规范了....
java
小码氓1 小时前
Java填充Word模板
java·开发语言·spring·word
会飞的天明1 小时前
Java 导出word 实现饼状图导出--可编辑数据
java·word
Muxiyale1 小时前
使用spring发送邮件,部署ECS服务器
java·服务器·spring