【问题标题】:Return indices of the two numbers such that they add up to a specific target返回两个数字的索引,使它们加起来为特定目标
【发布时间】:2019-03-30 19:29:45
【问题描述】:

我想解决以下问题:

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

我将以下数组作为输入 - [2, 7, 11, 15],目标 = 9。

因为 nums[0] + nums[1] = 2 + 7 = 9, 返回 [0, 1]。

这是我的代码 -

import java.util.Random;

public class TwoSum {

    static int[] numbers = new int[] {2, 7, 11, 15};
    int[] indices = new int[numbers.length];

    public static int[] returnIndices(int target, int[] inputArr) {
        int[] indices = new int[2];
        int randomOne = new Random().nextInt(inputArr.length);
        int randomTwo = new Random().nextInt(inputArr.length);
        while(true) {
            if(target == inputArr[randomOne] + inputArr[randomTwo]) {
                indices[0] = randomOne;
                indices[1] = randomTwo;
                break;
            }
        }
        System.out.println("done");
        return indices;
    }

    public static void main(String[] args) {
        int[] output = returnIndices(9, numbers);
    }

}

这是解决我的问题的正确方法吗?

【问题讨论】:

  • 您需要找到所有个这样的匹配索引对,还是可以在找到第一个时停止?
  • 我可以停止寻找第一个。我的程序甚至无法编译大声笑
  • doesn't even compile ... 鉴于您的代表水平,您不认为您至少应该发布有效的 Java 代码吗?
  • 你为什么选择随机索引而不是循环?
  • 你的程序有什么问题?

标签: java algorithm


【解决方案1】:

您可以使用hashmap以如下方式存储第一个数组:

   key  value(index in array)
    2 - 0
    7 - 1
    11 - 2
    15 - 3

接下来获取目标元素 9,并从索引 0 开始遍历给定数组。

索引 0 处的元素是 2 --> 计算 (9-2) = 7 --> 检查 7 是否是 hashmap 中的键

补充说明:以下情况需要注意:

arr = [3, 2, 1, 1] target = 6(在这种情况下不存在答案,但是通过上述方法,当您计算 6-3 = 3 时,您会得到索引 0 作为答案。)

但这可以通过检查 (target-arr[i] == arr[i]) 是否返回 true 来轻松解决。如果它返回 true 并且哈希图在键 arr[i] 处存储了两个索引,则将其作为答案返回,否则继续下一个元素。

【讨论】:

  • 也可能有助于通过列表向后工作 l
  • 如果您一次性寻找钥匙,那么6-3=3 问题将永远不会出现。
【解决方案2】:

有多种方法可以解决这个问题:

  1. Hashmap 方式 - @mettleap answer 涵盖了那个。
  2. Sort-Array 方式 - 我将向您解释它的伪代码。

让我们先举个例子来看看它的实际效果。我们在一个数组中得到arr = [5, 2, 1, 9, 7] 元素,如果我们可以得到8,我们将找到两个元素的索引。

如果你仔细观察,你会知道如果我们将数组中的第 3 个 + 最后一个元素相加,我们将得到8,这意味着24 将是我们的答案。 那么那里的土地怎么样?让我们一步一步来

  1. 维护一个相同大小的单独数组,它将在其初始设置中保存arr 的索引。

    [5, 2, 1, 9, 7] = arr
    [0, 1, 2, 3, 4] = index_arr
    
  2. 现在按升序对arr 进行排序,并对index_arr 进行排序,使arr 中的元素索引在其初始设置中仍然存在。

    [1, 2, 5, 7, 9] = arr
    [2, 1, 0, 4, 3] = index_arr
    
  3. 使用下面的伪代码:

    low  = 0
    high = length of arr - 1
    
    while (low < high) {
        sum = arr[low] + arr[high]
    
        if (sum  == number) {}
            print "index_arr[low]" and "index_arr[high]" 
            break the loop and exit
        } else if ( sum < number ) {
            low = low + 1
        } else {
            high = high - 1
        }
    }
    

    让我们看看实际的伪代码:

    [1, 2, 5, 7, 9] = arr
    [2, 1, 0, 4, 3] = index_arr
    
    Iteration # 01
    low = 0 and high = 4
    sum = arr[0] + arr[4] = 1 + 9 = 10
    10 > 8 , means 'else' will be executed high = high - 1 = 4 - 1 = 3
    
    Iteration # 02
    low = 0 and high = 3
    sum = arr[0] + arr[3] = 1 + 7 = 8
    8 == 8 , means first 'if' condiion will execute, and will indices and exit the loop
    

时间复杂度 - O(n)
空间复杂度 - O(n)

【讨论】:

    【解决方案3】:

    我已经在 c# 中尝试过,它可能会有所帮助..

    class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
                int[] nums = { 2, 7, 11, 15 };
                int target = 9;
                int[] result= TwoSumNumbers(nums, target);
            }
    
            public static int[] TwoSumNumbers(int[] nums, int target)
            {
                Dictionary<int, int> numsDict = new Dictionary<int, int>();
    
                for (int i = 0; i < nums.Length; i++)
                {
                    int num = nums[i];
    
                    if (numsDict.TryGetValue(target - num, out int index))
                    {
                        return new[] { index, i };
                    }
    
                    numsDict[num] = i;
                }
    
                return null;
            }
        }
    

    【讨论】:

      【解决方案4】:
      class Solution {
      public int[] twoSum(int[] nums, int target) {
          int [] answer = new int[2];
          Map<Integer,Integer> values = new HashMap<Integer,Integer>();
          for ( int i=0; i < nums.length; i++){
              values.put(nums[i],i);
          }
          for ( int i=0; i < nums.length; i++){
              int val = target - nums[i];
              Integer secondIndex = values.get(val);
              if ( secondIndex != null && secondIndex != i){
                  answer[0] = i;
                  answer[1] = secondIndex;
                  return answer;
              }
          }
          return answer;
      }
      

      }

      【讨论】:

        【解决方案5】:

        C#版本

                using System;
                using System.Collections.Generic;
                using System.Text;
                using System.Linq;
        
                namespace MyBasics
                {
                    class ArrayIndexForTarget
                    {
                        public static void Main()
                        {
                            ArrayIndexForTarget find = new ArrayIndexForTarget();
                            int[] arr = new int[] { 9, 2, 3, 9, 10 };
                            int target = 11;
                            var result = find.IndexFinder(arr, target);
            
                            Console.ReadKey();
                        }
                     public  int[]  IndexFinder(int[]myArray,int target)
                        {
                            int[] arr = new int[2];
                            Dictionary<int, int> dict = new Dictionary<int, int>();
        
                            for (int p=0; p < myArray.Length; p++) 
                            {
                                int numberToFind = target - myArray[p];
                                if (dict.ContainsValue(numberToFind))
                                {
                                    arr[0] = dict.FirstOrDefault(x => x.Value == numberToFind).Key;
                                    arr[1] = p;
                                    return arr;
                                }
                                else
                                {
                                    dict.Add(p,myArray[p]);
                                }
                            }
                            return arr;
        
                        }
                    }
                }
        

        【讨论】:

          【解决方案6】:
          class Solution {
              function twoSum($nums, $target) {        
                  $lenght = count($nums);
                  $indices = array();
                  for($i = 0; $i<$lenght-1; $i++){
                      for($j=$i+1; $j<$lenght; $j++){
                          if(($nums[$i]+$nums[$j]) == $target){
                              $indices[] = $i;
                              $indices[] = $j;
                              
                              return $indices;
                          }
                      }
                          
                  }
              } }
          

          【讨论】:

            【解决方案7】:
             private static int[] findNumbersToAdd(int target, int[] array) {
                int[] answer = {-1, -1};
                int length = array.length;
                for (int i = 0; i < length; i++) {
                    int var1 = array[i];
                    for (int j = i + 1; j < length; j++) {
                        int var2 = array[j];
                        if (var1 + var2 == target) {
                            answer[0] = i;
                            answer[1] = j;
                            break;
                        }
                    }
                }
                return answer;
            }
            

            【讨论】:

            • 你能解释一下为什么你的代码可以工作吗?仅代码答案被认为不是答案,并且可以删除。
            【解决方案8】:

            鉴于您不关注性能,我认为蛮力方法会很好。这是使用流和记录的解决方案。

            record IndexPair(int index1, int index2) { };
            IntStream.range(0, arr.length).boxed()
                .flatMap(i1 -> IntStream.range(i1, arr.length)
                    .filter(i2 -> arr[i1] + arr[i2] == target)
                    .mapToObj(i2 -> new IndexPair(i1, i2))
                .forEach(ip -> ...);
            

            如果您只想要一种解决方案,那么您可以使用findAny 而不是forEach

            【讨论】:

              【解决方案9】:
              public class Main {
              
              public static void main(String[] args) {
              int [] arr = {4,7,1,-3,2};
              
                  for(int i=0; i<arr.length-1; i++)
                  {
                      for(int j=0; j<=arr.length-2; j++)
                      {
                          if((arr[i]+arr[j+1])==6)
                          { 
                              System.out.println("indices = "+"["+i +","+(j+1)+"]");
                          }
                      }
                   }
                }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2019-12-23
                • 2018-03-09
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-06-06
                • 1970-01-01
                相关资源
                最近更新 更多