Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在整数数组中查找两个元素的和并返回两个元素第一次匹配的索引,对某些和不起作用';我很少工作_Java_Arrays_For Loop - Fatal编程技术网

Java 在整数数组中查找两个元素的和并返回两个元素第一次匹配的索引,对某些和不起作用';我很少工作

Java 在整数数组中查找两个元素的和并返回两个元素第一次匹配的索引,对某些和不起作用';我很少工作,java,arrays,for-loop,Java,Arrays,For Loop,我有一个问题,我们必须遍历数组,找到两个元素的索引,这两个元素与任何给定值匹配 我运行嵌套for循环遍历数组,并行检查两个元素的和,并返回两个元素的索引,如果它与答案匹配 class Solution { public int[] twoSum(int[] nums, int target) { int ans[] = new int[2]; int sum=0; int index=0; myloop: for (index=0; i

我有一个问题,我们必须遍历数组,找到两个元素的索引,这两个元素与任何给定值匹配

我运行嵌套for循环遍历数组,并行检查两个元素的和,并返回两个元素的索引,如果它与答案匹配

class Solution {
    public int[] twoSum(int[] nums, int target) {

        int ans[] = new int[2];
        int sum=0;
        int index=0;

myloop: for (index=0; index < nums.length; index++) {
             for (int index2 = index + 1 ; index2 < nums.length - 1; index2++) {
                sum = nums[index] + nums[index2];

                if (sum == target) {
                    ans[0]= index;
                    ans[1]= index2;
                    break myloop;
                }

                sum=0;
            }
        }

        return ans;
    }
}
类解决方案{
公共int[]twoSum(int[]nums,int目标){
int ans[]=新int[2];
整数和=0;
int指数=0;
myloop:for(index=0;index

它只适用于少数情况,不适用于少数情况,我得到了错误的输出。有什么建议吗?

内环条件
index2
不正确,应该是
index2
。例如,如果给你

nums = {1, 2, 3, 4} target = 7
您当前的代码

for (index=0; index < nums.length; index++) {
   for (int index2 = index + 1 ; index2 < nums.length - 1; index2++) {
       ...
   }

你能举例说明它适用于和不适用于哪些情况吗?工作输入:数组>[2,7,11,15]sum>9它适用于还是不适用于哪个情况?非工作输入:数组>[3,2,4]sum>6感谢输入,但即使在做了这些更改之后,它也不起作用。@Geek8Work:你能提供一个反例吗?1.工作输入:数组>[2,7,11,15]sum>9,2.非工作输入:数组>[[3,2,4]sum>6.你问过这个问题吗?请将内部循环更改为
(int index2=index+1;index2
;和
将myloop;
分解为
返回ans;
public int[] twoSum(int[] nums, int target) {
  for (int i = 0; i < nums.length; ++i) 
    for (int j = i + 1; j < nums.length; ++j) 
      if (nums[i] + nums[j] == target) 
        return new int[] {i, j};   // we've found it! Let's return it 

  return new int[0]; // let's return an empty array, not {0, 0} one  
}