两数之和_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))); } }

浙公网安备 33010602011771号