两数之和_LeetCode_1

LeetCode_1原题链接:https://leetcode-cn.com/problems/two-sum/

剑指 Offer 57原题链接:  https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/

复制代码
package Leetcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

/**
 * @date 2022/4/3-17:26
 * 给定一个整数数组 nums 和一个整数目标值 target,在该数组中找出和为目标值 target的那两个整数,
 * 并返回它们的数组下标。
 */
public class TwoSum_1 {

    // 解法一:双重循环,判断相加的结果
    public static int[] twoSum_1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }
        throw new IllegalArgumentException("No solution");
    }

    // 解法二:定义Map集合,每次判断差值是否存在map中
    public static int[] twoSum_2(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int temp = target - nums[i];
            if (map.containsKey(temp)) {
                return new int[] {map.get(temp), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No solution");
    }

    public static void main(String[] args) {
        // int[] nums = {1, 2, 3, 4};
        // int target = 6;
        System.out.println("Please input array separated by spaces or commas");
        Scanner in = new Scanner(System.in);
        String str = in.next().toString();
        String[] strArr = str.split(",");
        // String str = in.nextLine().toString();
        // String[] strArr = str.split(" ");
        int[] nums = new int[strArr.length];
        for (int i = 0; i < nums.length; i ++) {
            nums[i] = Integer.parseInt(strArr[i]);
        }
        System.out.println(Arrays.toString(nums));
        System.out.println("Please input the value of target");
        int target = in.nextInt();
        in.close();
        System.out.println(Arrays.toString(twoSum_1(nums, target)));
        System.out.println(Arrays.toString(twoSum_2(nums, target)));
    }
}
复制代码

 

posted @   2022年总冠军gogogo  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示