有 Java 编程相关的问题?

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

java在数组中添加twoNumber,并且必须等于目标

我有一个程序,其中输入数组“n”的元素数,然后输入目标“d”, 然后我想从矩阵中加上两个数字,加起来等于目标“d”, 然后我想返回这两个数字的索引数组 例如:

 Input: nums = [2,7,11,15], target = 9
 Output: [0,1]
 Output: Because nums[0] + nums[1] == 9, we return [0, 1].

我写了这个程序,但是我不能返回索引, 我怎样才能解决这个问题

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length - 1; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                System.out.println("This the number that we want it" + "\n" + i + "\n" + j);
            }
        }
    }
    return nums;
}

共 (2) 个答案

  1. # 1 楼答案

    看看这个解决方案

    时间复杂度O(n^2),空间复杂度O(1)

    public static int[] foo(int[] arr, int d) {
        for (int i = 0; i < arr.length - 1; i++)
            for (int j = i + 1; j < arr.length; j++)
                if (arr[i] + arr[j] == d)
                    return new int[] { i, j };
    
        return new int[] {-1, -1};
    }
    

    时间复杂性O(n),空间复杂性O(n)

    public static int[] foo(int[] arr, int d) {
        Map<Integer, Integer> map = new HashMap<>();
    
        for (int i = 0; i < arr.length; i++) {
            if (map.containsKey(d - arr[i]))
                return new int[] { map.get(d - arr[i]), i };
    
            map.put(arr[i], i);
        }
    
        return new int[] {-1, -1};
    }
    
  2. # 2 楼答案

    public int[] twoSum(int[] nums, int target) {
    
        int[] result = new int[2];
    
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    res[0] = i;
                    res[1] = j;
                    System.out.println("This the number that we want it" + "\n" + i + "\n" + j);
                }
            }
        }
    
        return res;
    }
    

    您需要创建一个大小为2的新数组并返回该数组


    如果你对O(n^2)的复杂性感到满意,你不需要提前阅读。但这里有一个时间复杂度为O(n)的解决方案:

    public int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
    
        for (int i = 0; i < numbers.length; map.put(numbers[i], ++i)) {
            if (map.containsKey(target - numbers[i])) {
                return new int[] {map.get(target - numbers[i]), i + 1};
            }
        }
    
        return new int[]{0,0};
    }