Leetcode Question 1: two numbers

Given an integer array nums and a target value target, and you find two integers target value in the array.
You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.
Example:
Given nums = [2, 7, 11 , 15], target = 9
because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]

Python:

nums = [2, 7, 11, 15, 29]
target = 17


# print(nums[0])


def calcOrder(nums, target):
    m = 0
    n = 0
    for i in range(len(nums) - 1):
        for j in range(i + 1, len(nums)):
            # print("i+j= ",nums[i]+nums[j])
            if nums[i] + nums[j] == target:
                # print(i, j)
                m, n = i, j
                # print("result1", m, n)
    return m, n


print(calcOrder(nums, target))

  

Java

public class SumOf2Nums {
	public static void main(String args[]) {
		int[] array1 = { 1, 4, 7, 11 };
		int target = 12;
		SumOf2Nums s2n = new SumOf2Nums();
		int[] orders = s2n.calcOrder(array1, target);
		for (int i = 0; i < orders.length; i++) {
			System.out.print(" " + orders[i]);
		}

	}

	public int[] calcOrder(int[] arr, int target) {
		int[] result = { 0, 0 };
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = i + 1; j < arr.length; j++) {
				if (arr[i] + arr[j] == target) {
					result[0] = i;
					result[1] = j;
				}
			}
		}
		return result;
	}
}

  

Tonight learning outcomes:

1, Python 110 interview questions see Question 25 https://www.cnblogs.com/lmx123/p/9230589.html

2, own independent realized leetcode Question 1

Guess you like

Origin www.cnblogs.com/flyingtester/p/12203840.html