笨蛋学算法之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);
        }
    }
}
相关推荐
czhc11400756637 分钟前
JAVA1026 方法;类:抽象类、抽象类继承;接口、接口继承 Linux:Mysql
java·linux·mysql
海梨花9 分钟前
【力扣Hot100】刷题日记
算法·leetcode·1024程序员节
一 乐21 分钟前
宠物管理|宠物店管理|基于SSM+vue的宠物店管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·宠物
hope_wisdom31 分钟前
C/C++数据结构之用链表实现栈
c语言·数据结构·c++·链表·
DuHz37 分钟前
使用稀疏采样方法减轻汽车雷达干扰——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理
gAlAxy...42 分钟前
面试JAVASE基础(五)——Java 集合体系
java·python·面试·1024程序员节
ceclar1231 小时前
C++容器list
java·c++·list
大肘子咒你1 小时前
数字狂潮来袭
数据结构·c++·1024程序员节
张较瘦_1 小时前
[论文阅读] 从 5MB 到 1.6GB 数据:Java/Scala/Python 在 Spark 中的性能表现全解析
java·python·scala
hansang_IR1 小时前
【算法速成课 3】康托展开(Cantor Expansion)/ 题解 P3014 [USACO11FEB] Cow Line S
c++·算法·状态压缩·康托展开·排列映射