Java Leetcode 两数之和

题目

两数之和 https://leetcode-cn.com/problems/two-sum/submissions/

解答结果

执行用时:45 ms, 在所有 Java 提交中击败了38.35% 的用户
内存消耗:41.1 MB, 在所有 Java 提交中击败了42.24% 的用户
通过测试用例:57 / 57

代码

package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

/**
 * @Author 夏秋初
 * @Date 2022/3/7 22:54
 */
class Solution {
    public static void main(String[] args) {
        int count;
        int[] array;
        int target;
        //
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入数组大小:");
        int num = scanner.nextInt();
        array = new int[num];
        //
        System.out.print("请输入数组元素:");
        for (int i = 0; i < num; i++) {
            array[i] = scanner.nextInt();
        }
        System.out.print("请输入两数之和:");
        target = scanner.nextInt();
        new Solution().twoSum(array, target);
    }

    public int[] twoSum(int[] nums, int target) {
//        for (int i = 0; i < nums.length; i++) {
//            for (int j = i; j < nums.length; j++) {
//                if(target == nums[i] + nums[j] && i != j){
//                    return new int[]{i, j};
//                }
//            }
//        }
//        return null;
        for (int i = 0; i < nums.length; i++) {
            int res = target - nums[i];
            for (int j = i; j < nums.length; j++) {
                if (nums[j] == res && i != j) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }
}
posted @   夏秋初  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2021-03-07 记录一次 electronjs 12.0.0 安装运行出现cli.js出错、以及获取不到nodeapi的问题(解决办法:版本不对导致的)
点击右上角即可分享
微信分享提示