gpt4 book ai didi

java - 在 Java 中为 Testdome 查找两个求和函数

转载 作者:行者123 更新时间:2023-12-02 10:23:07 26 4
gpt4 key购买 nike

我正在尝试解决 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]);
}
}

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

您可以将我的代码复制粘贴到在线网站中并查看结果。

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

提前致谢:)

最佳答案

通过 hashmap 使用动态编程,请记住 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;
}

关于java - 在 Java 中为 Testdome 查找两个求和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com