[Leetcode] Two Sum

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

 

Solution:

 1 public class Solution {
 2     public int[] twoSum(int[] numbers, int target) {
 3         int[] result = { -1, -1 };
 4         if (numbers.length < 2)
 5             return result;
 6         int[] copyNumbers = numbers.clone();
 7         Arrays.sort(copyNumbers);
 8         int low = 0;
 9         int high = copyNumbers.length - 1;
10         int num1 = 0, num2 = 0;
11         while (low < high) {
12             int temp = copyNumbers[low] + copyNumbers[high];
13             if (temp < target)
14                 low++;
15             else if (temp > target)
16                 high--;
17             else {
18                 num1 = copyNumbers[low];
19                 num2 = copyNumbers[high];
20                 break;
21             }
22         }
23         for (int i = 0; i < numbers.length; ++i) {
24             if (numbers[i] == num1 || numbers[i] == num2) {
25                 if (result[0] == -1)
26                     result[0] = i + 1;
27                 else
28                     result[1] = i + 1;
29             }
30         }
31         return result;
32     }
33 }

这里需要注意的是:

要返回的是index,所以得1.在复制后的copyNum里找到值,2. 在原num数组里通过值找到index。

 

posted @ 2014-11-01 00:59  Phoebe815  阅读(200)  评论(0编辑  收藏  举报