作业帮:给定一个整数数组,找出其中两个数相加等于目标值(去重set)
题目描述
给定一个整数数组,找出其中两个数相加等于目标值 输入 [1,3,5,7,9,11] 10 输出 1,9 3,7
代码:
import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String[] vals= str.substring(1, str.length()-1).split(","); int[] num = new int[vals.length]; for (int i = 0; i < num.length; i++) { num[i] = Integer.valueOf(vals[i]); } int sum = sc.nextInt(); HashSet<Integer> set = getNums(num, sum); for (Integer integer : set) { System.out.println(integer + "," + (sum-integer)); } } public static HashSet<Integer> getNums(int[] num, int sum){ HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < num.length; i++) { map.put(num[i], i); } for (int i = 0; i < num.length; i++) { int value = sum - num[i]; if(map.containsKey(value) && sum != 2*value){ if(!(set.contains(num[i])||set.contains(value))){ set.add(num[i]); continue; } } } return set; } }