笨蛋学算法之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);
        }
    }
}
相关推荐
岁忧17 分钟前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_78920 分钟前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
CJi0NG21 分钟前
【自用】JavaSE--算法、正则表达式、异常
java
Hellyc1 小时前
用户查询优惠券之缓存击穿
java·redis·缓存
今天又在摸鱼1 小时前
Maven
java·maven
老马啸西风1 小时前
maven 发布到中央仓库常用脚本-02
java·maven
代码的余温1 小时前
MyBatis集成Logback日志全攻略
java·tomcat·mybatis·logback
秋说2 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy2 小时前
力扣61.旋转链表
算法·leetcode·链表
一只叫煤球的猫3 小时前
【🤣离谱整活】我写了一篇程序员掉进 Java 异世界的短篇小说
java·后端·程序员