给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
你需要实现的函数twoSum
需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 0 到 n-1。样例
给出 numbers = [2, 7, 11, 15]
, target = 9
, 返回 [0, 1]
.
这道题也是很简单:遍历一下就好
Java版
public class Solution { /* * @param numbers: An array of Integer * @param target: target = numbers[index1] + numbers[index2] * @return: [index1 + 1, index2 + 1] (index1 < index2) */ public int[] twoSum(int[] numbers, int target) { // write your code here int length = numbers.length; int[] t = new int[2]; for(int i = 0 ; i < length ; i++){ for(int j = i+1 ; j<length ; j++){ if(numbers[i] + numbers[j] == target){ t[0] = i; t[1] = j; return t; } } } return null; } }
两层for循环感觉不大舒服,所以把其中一层搞掉换成if
改进的Python代码:
class Solution: """ @param: numbers: An array of Integer @param: target: target = numbers[index1] + numbers[index2] @return: [index1 + 1, index2 + 1] (index1 < index2) """ def twoSum(self, numbers, target): result = [] i = 0 j = 1 while i < len(numbers) and j != i: if target == (numbers[i]+numbers[j]): result.append(i) result.append(j) break elif j == len(numbers)-1: i = i + 1 j = i + 1 else: j = j+1 return result
加油!!!