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

No.001:Two Sum

时间:2016-09-22 01:07:19      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

问题:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

难度:

Easy

翻译:

给定一个整型数组和一个特殊值,返回数组中两数的下标,这两数的和为给定的特殊值,假定解唯一确定。

例子:

给定数组{2,7,11,15},特殊值9,返回下标[0,1]

思路:

1. 解唯一确定,是一个很重要的信息,将数组转为集合,利用集合的List.contains()方法,当前值a和sum-a都在集合中

解题中遇到的困难:

1. 数组转集合,容易出现如下错误:

1 int[] array = new int[length];
2 List<Integer> list = new ArrayList<>();
3 list = Arrays.asList(array);

这种情况下,编译器会报错,提示将第2行的List<Integer>转为List<int[]>。原因在于集合不会接收基本类型,而这种情况不会触发自动装箱,所以集合将int[]作为集合接收的类型。

2. 使用Arrays.asList(array)生成的集合,拥有不可使用add()和remove()一系列方法的特性,一旦使用,会抛出java.lang.UnsupportedOperationException,而且是运行时异常,编译器不会报错。

解题代码:

private static int[] method(int[] array, int sum) {
        // 结果数组
        int[] result = new int[2];
        // 保护无结果的标志位
        boolean flag = false;
        // 先将int[]转成Integer[]
        Integer[] collectionArray = new Integer[array.length];
        for (int i = 0; i < array.length; i++) {
            collectionArray[i] = array[i];
        }
        List<Integer> list = new ArrayList<>();
        list = Arrays.asList(collectionArray);
        list.remove(0);
        for (Integer a : list) {
            if (list.contains(sum - a)) {
                result[0] = list.indexOf(a);
                result[1] = list.lastIndexOf(sum - a);
                flag = true;
                break;
            }
        }
        if (flag) {
            return result;
        }
        return null;
    }

测试代码地址:

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q001.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

No.001:Two Sum

标签:

原文地址:http://www.cnblogs.com/jing-an-feng-shao/p/5894648.html

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