码迷,mamicode.com
首页 > 编程语言 > 详细

九章算法强化班全解

时间:2016-05-20 09:47:19      阅读:1296      评论:0      收藏:0      [点我收藏+]

标签:

第一周。

1,two sum。

技术分享
 Two Sum

 Description
 Notes
 Testcase
 Judge
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.

 Notice

You may assume that each input would have exactly one solution

Have you met this question in a real interview? Yes
Example
numbers=[2, 7, 11, 15], target=9

return [1, 2]
View Code

答案和解析:利用List来存前面出现过的元素,然后通过查找是否出现了target - 当前值的元素。来判断是否有组合对。

技术分享
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
        ArrayList<Integer> list = new ArrayList();
        int[] res = new int[2];
        for (int i = 0; i < numbers.length; ++i) {
            if (list.contains(target - numbers[i])) {
                res[0] = list.indexOf(target - numbers[i]) + 1;
                res[1] = i + 1;
                break;
            } else {
                list.add(numbers[i]);
            }
        }
        return res;
    }
}
View Code

 

九章算法强化班全解

标签:

原文地址:http://www.cnblogs.com/yueyebigdata/p/5510888.html

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