【问题标题】:TWO SUM PROBLEM IN JAVA - I coded the below code but unable to find the problem in thisJAVA 中的两个求和问题 - 我编写了以下代码,但无法在其中找到问题
【发布时间】:2022-07-18 01:48:19
【问题描述】:

给定一个整数数组 nums 和一个整数目标,返回两个数字的索引,使它们相加为目标。 您可能会假设每个输入都只有一个解决方案,并且您可能不会两次使用相同的元素。 您可以按任何顺序返回答案。 示例 1: 输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9,所以我们返回 [0, 1]。

   Hi Team,

   Above is my problem statement  and below is the code i coded.    /******************************************************************************

                       Online Java Compiler.
           Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it.
   *******************************************************************************/
   public class Main {  public static void main(String[] args) {
    int[] nums={2,7,8,0};
    int target=9;

   int s=0;
   for(int i=0;i<nums.length;i++)
   {
      for(int j=i+1;j<nums.length;j++) 
      {
          s=s+nums[i][j];
      }
         if(s==target)
   {
       System.out.print("["+i+","+j+"]");
   }
  } } }
   I am unable to understand what's the problem with compilation ,could    anyone help!->Main.java:20: error: array required, but int found    s=s+nums[i][j];    it shows this error`enter code here`

【问题讨论】:

  • 我无法理解这段代码有什么问题。

标签: arrays sum


【解决方案1】:

s=s+nums[i][j]; 行中,您正在以二维数组的形式访问nums

但是您将变量 nums 定义为一维数组。

如果您需要更多帮助,请回复。

【讨论】:

    【解决方案2】:

    类解决方案{ public int[] twoSum(int[] nums, int target) {

      int[] indexes = new int[2];
    
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                if(target ==nums[i]+nums[j]){
                    indexes[indexes.length-2] =i;
                    indexes[1] = j;
                }
            }
        }
    
        return indexes;
        
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 2022-06-15
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多