您的位置:首页 > 其它

LeetCode(二)关于TwoSum的实现

2014-04-17 17:30 274 查看

题目:

给定一个整数,从里面找出两个数,其和等于一个指定的整数。

程序返回这两个数在数组中的位置(数组下标从1开始),且位置小的在前面。

例如:数组 { 2, 7 , 11, 15}, 指定整数 = 9

返回:{1, 2}

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


解题思路:

1)复制一个数组出来,并将复制出来的数组进行从小到大的排序。

2)指定排序后数组中的第一个数为第一个数,最后一个数为第二个数,可知第一个数是数组中最小的数,第二个数是数组中最大的数。

3)比较两个数的和(sum)跟指定的整数(target)的大小,如果 sum 小于 target,由于第二数已经是最大的数了,则说明第一个数太小,所以第一个数向前移。反之,如果 sum 大于 target,由于第一个数已经是最小的数了,则说明第二个数太大,所以第二个数要往后移。

4)重复进行第三步,直到两个数之后 sum 刚好等于指定的整数 target。

5)找出这两个数在原来数组中的位置,返回下标。

代码:

public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[]{-1,-1};
int len = numbers.length;
int[] sortedNumbers = new int[len];
System.arraycopy(numbers, 0, sortedNumbers, 0, len);
int first = 0;
int second = len - 1;
Arrays.sort(sortedNumbers);
while(first < second){
if(sortedNumbers[first] + sortedNumbers[second] < target){
first++;
continue;
}
if(sortedNumbers[first] + sortedNumbers[second] > target){
second--;
continue;
}
break;
}
int n1 = sortedNumbers[first];
int n2 = sortedNumbers[second];

for (int i = 0; i < len; i++) {
if (n1 == numbers[i] || n2 == numbers[i]) {
if (result[0] == -1) {
result[0] = i + 1;
} else {
result[1] = i + 1;
break;
}
}
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode TwoSum