在Java中为Testdome找到两个求和函数

时间:2019-01-14 15:50:27

标签: java rpa

我正在尝试解决Java的testdome在线考试中的问题。

/*
 Problem statement: Write a function that, given a list and a target sum, 
returns zero-based indices of any two distinct elements whose sum is equal to the target sum. 
If there are no such elements, the function should return null.
For example, 
findTwoSum(new int[] { 3, 1, 5, 7, 5, 9 }, 10) should return a single dimensional array with two elements and contain any of the following pairs of indices:
0 and 3 (or 3 and 0) as 3 + 7 = 10
1 and 5 (or 5 and 1) as 1 + 9 = 10
2 and 4 (or 4 and 2) as 5 + 5 = 10

 My code gives the correct output but passes 3/4 tests

 The last test case which is failing says - code takes too long to answer when array has large # of elements

 */
--here is my code--

public class TwoSum {

    public static int[] findTwoSum(int[] list, int sum) {    
        int listLength=list.length;
        int[] match=new int[2];

        for(int i=0; i<listLength; i++){
            for(int j=i+1; j<listLength; j++){
                if(list[i]+list[j]==sum){
                    match[0]=i;
                    match[1]=j;
                    return match;
                }    
            }
        }
        return null;    
    }

    public static void main(String[] args) {
        int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 10);
        System.out.println(indices[0] + " " + indices[1]);
    }
}

请帮助我更正代码,以便它也可以通过第4个测试用例。

您可以将我的代码复制粘贴到在线网站上,然后查看结果。

https://www.testdome.com/d/java-interview-questions/4

预先感谢:)

1 个答案:

答案 0 :(得分:0)

使用带有哈希图的动态编程,请记住import java.util.HashMap;import java.util.Map;

public static int[] findTwoSum(int[] list, int sum) 
{
        Map<Integer, Integer> hmap = new HashMap<>();
        for (int i=0; i<list.length; i++) 
        {
            int req = sum - list[i];
            if (hmap.get(req) != null) 
                return new int[]{i, hmap.get(req)};

            hmap.put(list[i], i);
        }

        return null;    
}