有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java返回两个数字的索引,这样它们加起来就是一个特定的目标

我想解决以下问题:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

我将下面的数组作为输入-[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);
    }

}

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


共 (4) 个答案

  1. # 1 楼答案

    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;
                    }
                }
                    
            }
        } }
    
  2. # 2 楼答案

    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;
    
                    }
                }
            }
    
  3. # 3 楼答案

    可以使用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,并且hashmap在键arr[i]处存储了两个索引,则将其作为答案返回,否则继续下一个元素

  4. # 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;
    }
    

    }