在Java中查找Testdome的两个求和函数

在Java中查找Testdome的两个求和函数,java,rpa,Java,Rpa,我试图解决testdome Java在线考试中的一个问题 /* 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 shou

我试图解决testdome Java在线考试中的一个问题

/*
 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]);
    }
}
/*
问题陈述:编写一个函数,给定一个列表和一个目标和,
返回其和等于目标和的任意两个不同元素的从零开始的索引。
如果没有这样的元素,函数应该返回null。
例如
findTwoSum(新int[]{3,1,5,7,5,9},10)应返回一个包含两个元素的一维数组,并包含以下任何一对索引:
0和3(或3和0)等于3+7=10
1和5(或5和1)等于1+9=10
2和4(或4和2)等于5+5=10
我的代码给出了正确的输出,但通过了3/4测试
最后一个失败的测试用例是,当数组中有大量元素时,代码需要很长时间才能回答
*/
--这是我的密码--
公共类二和{
公共静态int[]findTwoSum(int[]列表,int-sum){
int listLength=list.length;
int[]匹配=新int[2];

对于(inti=0;i使用动态编程和hashmap,请记住
导入java.util.hashmap;
导入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;    
}
公共静态int[]findTwoSum(int[]list,int-sum)
{
Map hmap=newhashmap();

对于(int i=0;我会来到Stackoverflow!这不是一个“请为我编写/修复我的代码”的网站,而是一个帮助解决特定编程问题的Q+a网站。如果你有一个特定的问题,你可以编辑这个问题来问它,但这里没有人会帮你修复它。有关更多信息,请参阅和。