首页 > 编程语言 > 详细

九章算法强化班全解

时间:2016-05-20 09:46:02      阅读:250      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!