Leetcode第1题:两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [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;
	}
}

今晚学习成果:

1、Python面试110题看到第25题https://www.cnblogs.com/lmx123/p/9230589.html

2、自己独立实现了leetcode第1题