LintCode 演算法(簡單)兩數之和
阿新 • • 發佈:2019-01-28
題目
給一個整數陣列,找到兩個數使得他們的和等於一個給定的數 target。
你需要實現的函式twoSum需要返回這兩個數的下標, 並且第一個下標小於第二個下標。注意這裡下標的範圍是 0 到 n-1。
樣例
給出 numbers = [2, 7, 11, 15], target = 9, 返回 [0, 1].
挑戰
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 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] numbers, int target) {
// write your code here
int a,b;
int[] reslut=new int[]{-1,-1};
for(int i=0;i<numbers.length;i++)
{
int searschNum=target-numbers[i];
for(int j=0;j<numbers.length;j++)
{
if (i!=j)
{
if(numbers[j]==searschNum)
{
if(i<j)
{
reslut[0]=i;
reslut[1]=j;
}else
{
reslut[0 ]=j;
reslut[1]=i;
}
break;
}
}
}
}
return reslut;
}
}