笨蛋学算法之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);
        }
    }
}
相关推荐
悟能不能悟2 分钟前
java Date转换为string
java·开发语言
菜宾9 分钟前
java-redis面试题
java·开发语言·redis
We་ct10 分钟前
LeetCode 125. 验证回文串:双指针解法全解析与优化
前端·算法·leetcode·typescript
客卿12313 分钟前
力扣20-有效括号(多家面试题)
算法·leetcode·职场和发展
猿小羽16 分钟前
AI 学习与实战系列:Spring AI + MCP 深度实战——构建标准化、可扩展的智能 Agent 系统
java·spring boot·llm·agent·spring ai·mcp·model context protocol
木井巳25 分钟前
【递归算法】快速幂解决 pow(x,n)
java·算法·leetcode·深度优先
苦藤新鸡29 分钟前
41.有序数组(二叉搜索树)转平衡二叉树
数据结构·力扣
风景的人生39 分钟前
mybatis映射时候的注意点
java·mybatis
墨夶40 分钟前
Java冷热钱包:不是所有钱包都叫“双保险“!用户资产安全的终极守护者
java·安全·区块链
Maỿbe1 小时前
重走力扣hot的矩阵
算法·leetcode·矩阵