給一個整數數組,找到兩個數使得他們的和等於一個給定的數 target。
你需要實現的函數twoSum
需要返回這兩個數的下標, 並且第一個下標小於第二個下標。注意這裏下標的範圍是 0 到 n-1。
樣例
Example1:
給出 numbers = [2, 7, 11, 15], target = 9, 返回 [0, 1].
Example2:
給出 numbers = [15, 2, 7, 11], target = 9, 返回 [1, 2].
挑戰
Either of the following solutions are acceptable:
- O(n) Space, O(nlogn) Time
- O(n) Space, O(n) Time
注意事項
你可以假設只有一組答案。
public class Solution {
/**
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1, index2] (index1 < index2)
*/
public int[] twoSum(int[] numbers, int target) {
// write your code here
int result[] = new int[2];
for(int i = 0;i<numbers.length;i++){
for(int j = i+1;j<numbers.length;j++){
if((numbers[i]+numbers[j]) == target){
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
}