码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Two Sum

时间:2014-11-01 06:12:44      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   for   sp   div   

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。

 

[Leetcode] Two Sum

标签:style   blog   io   color   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/Phoebe815/p/4066299.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!