24小时在线 - 古典小说 - 文学小说 - 关于我们
您的当前位置:首页 > Java > 其它 >

一. Two Sum

来源:比特技术 编辑:比特技术网 时间:2018-06-04点击:
导读:1. Two Sum题目: Given an array of integers, find two
1. 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

链接: http://leetcode.com/problems/two-sum/

题解:

使用HashMap,一次遍历数组,Time Complexity - O(n),Space Complexity - O(n)

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int result[] = {-1, -1};
        if(numbers == null || numbers.length == 0)
            return result;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < numbers.length; i++){
            if(!map.containsKey(target - numbers[i]))
                map.put(numbers[i], i);
            else{
                result[0] = map.get(target - numbers[i]) + 1;
                result[1] = i + 1;
                break;
           }    
        }
        return result;
    }
}

 

Reference:

http://www.cnblogs.com/springfor/p/3859618.html

来源:比特技术在线(www.byte.online),欢迎分享本文,转载请保留出处!
http://www.byte.online/a/Java/qita/2018/223740.html
责任编辑:比特技术网

    打赏

    取消

    感谢您的支持,我会继续努力的!

    扫码支持
    扫码打赏,你说多少就多少

    打开支付宝扫一扫,即可进行扫码打赏哦

    网友评论:

    Copyright © www.byte.online 比特技术在线 版权所有 粤ICP备15038486号-3
    本站所有资料来源于网络,由个人收集整理,仅限于个人学习和研究,如果侵犯您的权益请联系我们删除!
    Top