从数组中找出两个数据的位置,该两个数据的和等于给定的目标数据

public static void main(String args[]) {
        int[] result = twoSum(new int[]{-1, 0, 1, 3, 4}, 7);
        System.out.println(result);
    }

public static int[] twoSum(int[] numbers, int target) {
        int size = numbers.length;
        int[] result = new int[2];
        for (int i = 0; i < size; i++) {
            int current = numbers[i];
            if (current > target) {
                continue;
            }
            int targetNum = target - current;
            for (int j = 0; j < size; j++) {
                if (numbers[j] == targetNum && j != i) {
                    if (j > i) {
                        result[0] = i + 1;
                        result[1] = j + 1;
                    } else {
                        result[0] = j + 1;
                        result[1] = i + 1;
                    }

                    return result;
                }
            }
        }
        return null;
    }

你可能感兴趣的:(从数组中找出两个数据的位置,该两个数据的和等于给定的目标数据)