简体   繁体   English

编写一个程序,将正数和负数数组(不包括 0)作为输入

[英]Write a program that takes as input an array of positive and negative numbers (0 excluded)

Write a program in java that takes as input an array of positive and negative numbers (0 excluded).在 java 中编写一个程序,将正负数数组(不包括 0)作为输入。 The objective is to return those items from the array whose sum is 0. If no such items exist return “No Elements found” Example: For an input array [-4, 1, 3, -2, -1], one of the possible results would be 3, -2, -1 since their sum is 0. Note: If there are more than 1 combination of such items, you can return any 1 of them目标是返回数组中总和为 0 的那些项。如果不存在此类项,则返回“未找到元素”示例:对于输入数组 [-4, 1, 3, -2, -1],其中一个可能的结果为 3、-2、-1,因为它们的总和为 0。注意:如果此类项目的组合超过 1 种,您可以返回其中任意 1 种

its my try这是我的尝试

class Solution {
   
        public int[] twoSum(int[] numbers, int target) {
    int[] result = new int[2];
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(target - numbers[i])) {
            result[1] = i;
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        map.put(numbers[i], i);
    }
    return result;
}}
    

but I can't find the Ans can anyone help me out但我找不到 Ans 任何人都可以帮助我

Here is a recursive solution:这是一个递归解决方案:

public static int[] twoSum(int[] numbers) {
    List<Integer> list = new ArrayList<>();
    boolean found = twoSum(numbers, 0, 0, list);
    if (found) {
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
    return null;
}

public static boolean twoSum(int[] numbers, int from, int target,
        List<Integer> list) {
    for (int i = from; i < numbers.length; i++) {
        int current = numbers[i];
        list.add(current);
        int newTarget = target-current;
        if (newTarget == 0) {
            return true;
        }
        boolean found = twoSum(numbers, i+1, newTarget, list);
        if (found) {
            return true;
        }
        list.remove(list.size()-1);
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM